创建Pi位数的直方图

时间:2018-07-15 23:20:30

标签: python python-3.x graphing

我在绘制Pi的前一百万个数字分布的直方图时遇到麻烦。

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
# import pandas as pd

"""
This program charts a histogram of the distribution of the digits in pi.
"""
# Assign variable to the 1 Million digits of Pi
file_object = open('pi_million_digits.txt', 'r')
pi = file_object.read()

# Add the million digits to a list for plotting.
digit_list = []
for digit in pi:
    digit_list.append(digit)

# Plot the histogram
bins = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

plt.hist(digit_list, bins, histtype = 'bar', rwidth = 0.5)

plt.title('Distribution of Digits in Pi')
plt.xlabel('Digits')
plt.ylabel('Times appeared in the first million digits of Pi')

plt.show()

此代码将所有数字都转储到一个bin中,我不知道如何将每个数字分配到其各自的bin中。

此代码还尝试绘制Pi中的小数点,但我现在不太担心要解决这个问题。

感谢您提供任何清理和修复图形的帮助。

Here is a link for the first million digits of pi to save as a .txt doc

1 个答案:

答案 0 :(得分:3)

您的问题是,当您从文件中读取数字时,它们都被视为字符串。您需要做的是将每个数字都转换为带有

的整数
digit_list.append(int(digit))

-,以便根据您提供的bin对它们进行分箱。