# 用Python进行有进度条的π计算

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)):

2.2文本进度条

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()))

(0)
(0)