Happy Pi day 查看pi中数字出现的次数

学习一个公式可以比较快速的计算出pi的若干精度
核心的算法是:
%E5%9B%BE%E7%89%87.png
使用Python实现函数cal_pi(n):
from decimal import Decimal
from decimal import getcontext
def cal_pi(precision):
    getcontext().prec=precision
    return sum(1/Decimal(16)**k*(Decimal(4)/(8*k+1)-Decimal(2)/(8*k+4)-Decimal(1)/(8*k+5)-Decimal(1)/(8*k+6)) for k in range(precision))
尝试计算一下cal_pi(100)和cal_pi(1000):
print(cal_pi(100))
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117070
把100位的Pi计算出来,保存到字符串里面
#保存100位的pi
pi_100=cal_pi(100);
print(pi_100)
#查看100位的pi的长度
print(len(str(pi_100)))
#去掉.之后的长度
print(len(str(pi_100).replace('.','')))
#数字转换为字符串,并且取消掉.
pi_100_str=str(pi_100).replace('.',"")
#计算所有的数字的和
print(sum(map(int,pi_100_str)))
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117070
101
100
465
查看一下100位的pi中数字出现的个数-使用直方图
plt.hist(list(pi_100_str))
plt.xlabel('number')
plt.ylabel('times of number')
plt.title("times of numbers in pi")
得到的图形是,但是没有排序:

查看一下10000位的pi中的数字出现的个数-使用折线图
def plot_pi(n):
    pi_100_str=str(cal_pi(n)).replace('.',"")
    #统计每个数字出现的次数#这样得到的只是Key排序,这样是不行的
    print('fail:')
    print(sorted({a:pi_100_str.count(a) for a in set(pi_100_str)}))
    #把数据放到字典里面
    print('before sort:')
    dict1={a:pi_100_str.count(a) for a in set(pi_100_str)}
    print(dict1)
    #key排序
    list1=sorted(dict1.items(),key=lambda x:x[0])#取出字典的所有的元素,按照第一个key进行排序
    print('after sort:')
    print(list1)
    listx=[]
    listy=[]
    for x,y  in list1:
        listx.append(x)
        listy.append(y)
        #print(x,y)
    import matplotlib.pyplot as plt
    import numpy as np
    fig, ax = plt.subplots()  # Create a figure containing a single axes.
    ax.plot(listx,listy,label='num in pi') # Plot some data on the axes.
    ax.set_xlabel('number')
    ax.set_ylabel('times of number')
    plt.ylim(0,n/9)
    ax.set_title("times of numbers in pi")
    ax.legend() 
plot_pi(10000)
得到的结果是:
fail:
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
before sort:
{'7': 969, '1': 1026, '2': 1021, '3': 976, '4': 1012, '0': 968, '9': 1015, '8': 947, '5': 1046, '6': 1020}
after sort:
[('0', 968), ('1', 1026), ('2', 1021), ('3', 976), ('4', 1012), ('5', 1046), ('6', 1020), ('7', 969), ('8', 947), ('9', 1015)]
得到的图形是:
  

-THE END at Saturday, March 14, 2020 10:04:25 PM-
posted @ 2020-03-14 22:07  kongchung  阅读(289)  评论(0编辑  收藏  举报