简体   繁体   English

创建Pi的数字直方图

[英]Creating a Histogram of the digits of Pi

I'm having trouble plotting a histogram of the distribution of the first million 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()

This code dumps all digits into one bin, and I can't figure out how to assign each digit to its respective bin. 此代码将所有数字转储到一个bin中,我无法弄清楚如何将每个数字分配到其各自的bin。

This code also tries to graph the decimal point in Pi but I'm not too concerned about fixing that right now. 这段代码也试图在Pi中绘制小数点,但我现在并不太关心修复它。

Any help on cleaning this up and fixing the graph is appreciated. 任何有关清理和修复图表的帮助表示赞赏。

Here is a link for the first million digits of pi to save as a .txt doc 这是pi的第一百万个数字的链接,以保存为.txt文档

Your issue is that as your read your digits from a file, they are all treated as strings. 您的问题是,当您从文件中读取数字时,它们都被视为字符串。 What you need to do is cast each digit to an integer with 你需要做的是将每个数字转换成一个整数

digit_list.append(int(digit))

-in order for them to be binned according to your bin you provided. - 根据您提供的bin订购它们。

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

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