一、计算圆周率PI的方法
(一)公式法:
1 #CalPiV1.py 2 pi = 0 3 N = 100 4 for k in range(N): 5 pi += 1/pow(16, k) * (4 / (8 * k + 1) - 2 /(8 * k + 4) - 1/(8 * k + 5) - 1 /(8 * k + 6)) 6 print("圆周率值是:{}".format(pi))
(二)蒙特卡罗方法:
1 #CalPiV2.py 2 from random import random 3 from time import perf_counter 4 DARTS = 1000*1000*10 5 hits = 0.0 6 start = perf_counter() 7 for i in range(1, DARTS+1): 8 x, y = random(), random() 9 dist = pow(x**2 + y**2, 0.5) 10 if dist <= 1.0: 11 hits = hits + 1 12 pi = 4 * (hits/DARTS) 13 print("圆周率值是: {}".format(pi)) 14 print("运行时间是: {:.5f}s".format(perf_counter()-start))
算法说明:增加DARTS的位数,圆周率PI小数点后的位数就会增加。
(三)程序执行效果如下:
二、进度条的设计
(一)带刷新的文本进度条:
1 #TextProBarV3.py 2 import time 3 from tqdm import tqdm 4 scale = 50 5 print("执行开始".center(scale//2, "-")) 6 start = time.perf_counter() 7 for i in range(scale + 1): 8 a = '*' * i 9 b = '.' * (scale - i) 10 c = (i/scale)*100 11 dur = time.perf_counter() - start 12 print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,dur),end="") 13 time.sleep(0.1) 14 print("\n"+"执行结束".center(scale//2, '-'))
程序运行结束的静态图:
三、(一)最终代码:
1 from math import sqrt 2 from tqdm import tqdm 3 from random import random 4 import time 5 DARTS=10000 6 hits=0.0 7 t=time.perf_counter() 8 for i in tqdm(range(1,DARTS+1)): 9 x,y=random(),random() 10 dist=pow(x**2+y**2, 0.5) 11 if dist<=1.0: 12 hits+=1 13 a='*'*i 14 b='.'*(DARTS+1-i) 15 c=(i/DARTS+1)*100 16 t-=time.perf_counter() 17 time.sleep(0.00001) 18 pi=4*(hits/DARTS) 19 print("Pi值是{}.".format(pi)) 20 print("\t{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,-t),end='') 21 print("运行时间是:{:.5f}s".format(time.perf_counter()))
(二)程序运行效果图如下: