簡體   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