用python计算圆周率PI
一、计算圆周率PI的方法 (一)公式法: 1 #CalPiV1.py 2 pi = 0 3 N = 100 4 for k in range(N): 5 pi += 1/pow(16, k) * (4 / (8 * k + 1) - 2 /(8 * k + 4) - 1/(8 * k + 5) - 1 /(8 * k + 6)) 6 print("圆周率值是:{}".format(pi)) (二)蒙特卡罗方法: 1 #CalPiV2.py 2 from random import random 3 from time import perf_counter 4 DARTS = 1000*1000*10 5 hits = 0.0 6 start = perf_counter() 7 for i in range(1, DARTS+1): 8 x, y = random(), random() 9 dist = pow(x**2 + y**2, 0.5) 10 if dist <= 1.0: 11 hits = hits + 1 12 pi = 4 * (hits/DARTS) 13 print("圆周率值是: {}".format(pi)) 14 print("运行时间是: {:.5f}s".format(perf_counter()-start)) 算法说明:增加DARTS的位数