python——圆周率(蒙特卡洛)

使用蒙特卡洛法计算圆周率

#圆周率(蒙特卡洛)
from random import random
from time import perf_counter
a = 1000000   #进行1000000次模拟
b = 0.0
start = perf_counter()
for i in range(1, a+1):
    x, y = random(), random()
    dist = pow(x ** 2 + y ** 2, 0.5)
    if dist <= 1.0:
        b = b + 1
pi = 4 * (b/a)    
print("圆周率值是: {}".format(pi))
print("运行时间是: {:.5f}s".format(perf_counter() - start))
发布了11 篇原创文章 · 获赞 1 · 访问量 678

猜你喜欢

转载自blog.csdn.net/Otis_98/article/details/105193997