版权声明:本文为博主原创文章,转载请务必注明出处和作者,谢谢合作! https://blog.csdn.net/zhanshen112/article/details/87888617
一种是数学公式:
code:
#CalPiV1.py
pi=0
N=100
for i in range(N):
pi+=1/pow(16,i)*(4/(8*i+1)-\
2/(8*i+4)-1/(8*i+5)-1/(8*i+6))
print(pi)
第二种是使用蒙特卡罗方法:
code:
#CalPiV2.py
import random
import time
N=1000*1000
k=0
start=time.perf_counter()
for i in range(N):
x,y=random.random(),random.random()
dist=pow(x**2+y**2,0.5)
if dist<=1.0:
k+=1
pi=4*(k/N)
print("pi={},run time={:.2f}s".format(pi,time.perf_counter()-start))