繁体   English   中英

创建Pi的数字直方图

[英]Creating a Histogram of the digits of Pi

我无法绘制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中绘制小数点,但我现在并不太关心修复它。

任何有关清理和修复图表的帮助表示赞赏。

这是pi的第一百万个数字的链接,以保存为.txt文档

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

digit_list.append(int(digit))

- 根据您提供的bin订购它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM