Python 计算π及进度条显示

一,首先打开命令提示符找到Python路径,输入pip install tqdm下载第三方库tpdm。

二,写程序

法一

from math import *
from tqdm import tqdm
from time import *
total,s,n,t=0.0,1,1.0,1.0
clock()
while(fabs(t)>=1e-6):
    total+=t
    n+=2 
    s=-s
    t=s/n
k=total*4
print("π值是{:.10f}  运行时间为{:.4f}秒".format(k,clock()))
for i in tqdm(range(101)):
    print("
{:3}%".format(i),end="")
    sleep((clock())/100)#用执行程序的总时间来算出进度条间隔的时间

 运行结果如下 :

法二:

from random import random
from math import sqrt
from time import *
from tqdm import tqdm
DARTS=10000000
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)
for i in tqdm(range(10)):
    print("
{:3}%".format(i/10*100),end="") #这里的i/10*100指每10%显示一次
    sleep((clock())/100)#用执行程序的总时间来算出进度条间隔的时间  
print("pi的值{}.".format(pi))
print("运行时间:{:.5f}s".format(clock()))

  

原文地址:https://www.cnblogs.com/foldline/p/10568430.html