(1)(3)
答:用蒙特卡洛法计算pi
from random import random
from time import perf_counter
DARTS = 1000
hits = 0.0
start = perf_counter()
for i in range(1, DARTS+1):
x, y = random(), random()
dist = pow(x2 + y2, 0.5)
if dist <= 1.0:
hits = hits + 1
pi = 4 * (hits/DARTS)
print(“圆周率值是: {}”.format(pi))
print(“运行时间是: {:.5f}s”.format(perf_counter()-start))
(2)带进度条的圆周率计算
import math
import time
scale=20
t=time.process_time()
for i in range(scale+1):
a,b=’**'i,’…’(scale-i)
c=(i/scale)100
π=4(4*math.atan(1/5)-math.atan(1/239))
print("%[{:3}{}->{}]".format(a,b,c))
time.sleep(0.1)
print(π)
print("{:.2f}s".format(t))
print(“执行结束”)
有进度条的圆周率计算
最新推荐文章于 2022-03-19 18:31:21 发布