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))
|