圆周率的计算2
# CalPiVer2# 蒙特卡罗的随机投掷石子的比例计算方法
from random import random
from time import perf_counter
DARTS = 1000*1000
hits = 0# 记录在园内的数量
start = perf_counter()# 开始计时
for i in range(1, DARTS + 1):
x, y = random(), random()
dist = pow(pow(x,2) + pow(y,2), 0.5)
if dist <= 1:
hits += 1
pi = 4* hits/DARTS
end = perf_counter()# 计时结束
print("Pi的值为:%.10f" % pi )
print("计算时间为:%.2f" % (end - start) )
页:
[1]