π

 

一、写代码的准备工作:用pip下载第三方库tqdm

步骤1:打开cmd

步骤2:输入pip install   你要安装的库(如 pip install tqdm)

 

二、写程序

1.这个代码是由c语言的一道例题改编的

代码如下:

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("\r{:3}%".format(i),end="")
sleep((clock())/100)

效果如下:

2.第二个程序是根据python书上的

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("\r{:3}%".format(i/10*100),end="") 

sleep((clock())/100)#用执行程序的总时间来算出进度条间隔的时间

print("pi的值{}.".format(pi))print("运行时间:{:.5f}s".format(clock()))

效果如下:

 

posted on 2019-03-20 23:34  ljhhhhhh  阅读(501)  评论(0)    收藏  举报