4.5 pytho循环应用:蒙特卡洛方法计算圆周率

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# 圆周率计算 蒙特卡洛
import random
import 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 = hits + 1
pi = 4 * (hits/darts)
print("圆周率的值:{}".format(pi))
print("运行时间是:{:.5f}s".format(time.perf_counter()-start))
Licensed under CC BY-NC-SA 4.0
© ziyue.tech版权所有
Built with Hugo
主题 OoO落墨灼夭 设计

本站访问量:   您是本站第 位访问者