我在绘制 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()
此代码将所有数字转储到一个容器中,但我不知道如何将每个数字分配到其各自的容器中。
此代码还尝试绘制 Pi 中的小数点图形,但我现在不太关心修复该问题。
任何关于清理这个问题和修复图表的帮助都是值得赞赏的。
Here is a link for the first million digits of pi to save as a .txt doc
最佳答案
您的问题是,当您从文件中读取数字时,它们都被视为字符串。您需要做的是将每个数字转换为整数
digit_list.append(int(digit))
-以便根据您提供的 bin
对它们进行分类。
关于python - 创建 Pi 数字的直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51352925/