用python计算圆周率并用进度条提示算的进度
一、蒙特卡罗法计算pi
#e6.1CalPi.py 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): #蒙特卡罗(洒点法)法求pi
x, y = random(), random() dist = sqrt(x ** 2 + y ** 2) if dist <= 1.0: hits = hits + 1 if i ==DARTS*0.01*a: #进度条设置 print(" %{}[{}->{}]".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))
运行结果:
第一种进度条:
第二种进度条:
二、几何法计算pi
from math import sqrt import time n=int(input()) #参数n是对正六边形分割的次数 a=0.5 b=0 c=0 d=0.5 for i in range(n): b=sqrt(1-a*a) c=(1-b)*0.5 d=sqrt(c) a=d j=pow(2,n)*3 pi=2*d*j print("执行开始") #设置进度条 t=time.process_time() for i in range(11): e,f='**'*i,'..'*(9) g=(i/10)*100 pi=2*d*j print("%{:3}[{}->{}]".format(e,f,g)) time.sleep(0.1) print(pi) print("{:.2f}s".format(t)) print("执行结束")
运行结果: