1.tqdm是一个强大的终端进度条工具,我利用pip获取tqdm函数库。
2编写代码
2.1进行π的计算
from random import random
from math import sqrt
from time import clock
DARTS=10000
hits=0.0
clock()
for i in range(1,DARTS+1):
x,y=random(),random()
dist=sqrt(x**2+y**2)
if dist <=1.0:
hits=hits+1
pi=4*(hits/DARTS)
print("pi的值{}.".format(pi))
print("运行时间:{:.5f}s".format(clock()))for i in tqdm(range(10)):
然后改变DARTS的赋值,发现π的位数越来越多
2.2文本进度条
选择带刷新的文本进度条,利用tqdm库实现
代码:
import time
from tqdm import tqdm
scale=50
print("执行开始".center(scale//2,'-'))
t=time.clock()
for i in tqdm(range(scale+1)):
a='*'*i
b='.'*(scale-i)
c=(i/scale)*100
t-=time.clock()
print("\t{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,-t),end='')
time.sleep(0.05)
print("\n"+"执行结
2.3最后将两者结合
from math import sqrt
from tqdm import tqdm
from random import random
import time
DARTS=10000
hits=0.0
t=time.clock()
for i in tqdm(range(1,DARTS+1)):
x,y=random(),random()
dist=sqrt(x**2+y**2)
if dist<=1.0:
hits+=1
a='*'*i
b='.'*(DARTS+1-i)
c=(i/DARTS+1)*100
t-=time.clock()
time.sleep(0.00001)
pi=4*(hits/DARTS)
print("Pi值是{}.".format(pi))
print("\t{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,-t),end='')
print("运行时间是:{:.5f}s".format(time.clock()))