#CalPi.py
import random, time
DARTS = 1000*1000
hits = 0.0
start = time.perf_counter()
for i in range(1, DARTS+1):
x, y = random.random(), random.random()
dist = pow(x ** 2 + y ** 2, 0.5)
if dist <=1.0:
hits += 1
pi = 4 * (hits/DARTS)
print("圆周率值是:{}".format(pi))
print("运行时间是:{:.5f}s".format(time.perf_counter()-start))
如上图所示,第一象限的1/4个圆的面积为:1/4π*r*r
1/4个正方形的面积为:1
对于蒙特卡罗随机抛洒:扇形内的点数目为hits
正方形内的点的数目为DARTS
综上,(1/4πr*r)/1 = hits/DARTS
π = 4hits/DARTS