python计算近似圆周率

# 近似的计算圆周率方法,百度谷歌都搜索不到作者的方法
a=0
b=100
for k in range(b):
    a +=1/pow(16,k)*(4/(8*k+1)-2/(8*k+4)-1/(8*k+5)-1/(8*k+6))
print(a)
# pow()函数pow(10,2) 表示为10的2次方

# 使用蒙特卡罗方法
from random import random #生成0-1的小数值
from time import perf_counter
DARTS =1000*1000 #设置点的总数量  数量越大,计算时间越长
hits = 0.0 #设置目前在圆的内部点数
start = perf_counter() #当前系统时间的一个值
#对所有的点做一个循环运算
for i in range(1,DARTS+1): #对所有点进行抛撒
    x,y =random(),random() #两个坐标随机值
    dist = pow(x**2 +y**2,0.5)# 取两个坐标的平方和,再进行开方,取得值判断该点距离圆心的距离
    # 注意得出的仅仅为1个四分之一的圆,并不是整个圆最终结果需要*4
    # dist = pow(pow(x,2)+pow(y,2),0.5)
    if dist <=1.0: #如果距离小于或等于1.0那么他就在圆里面
        hits=hits +1#统计加1
pi = 4 *(hits/DARTS)
print(pi)
end = perf_counter() - start #运算时间=运算结束时间减去未运算时的时间
print("运算时间为{:.5f}".format(end)) #保留后精确5位

猜你喜欢

转载自blog.csdn.net/weixin_47021806/article/details/114946563