用python计算圆周率PI

发布时间 2023-10-29 22:34:30作者: 过过过过过过

from random import random
from math import sqrt
import time
DARTS=10**7
hits=0.0
a=1
start=time.perf_counter()
for i in range(1,DARTS+1):
x,y=random(),random()
dist=sqrt(x**2+y**2)
if dist<=1.0:
hits=hits+1

if i==DARTS*0.01*a:
print("\r%{}[{}->{}]".format(a,'*'*a,'-'*(10-a)),end="")
a+=3
pi=4*(hits/DARTS)
end=time.perf_counter()
print("pi值是{}.".format(pi))
print("运行时间是:{:5.5}s".format(end-start))