计算pi的精度+进度条显示

步骤1:安装tqdm

首先,要打开cmd,输入指令,不断找到python文件的路径,知道找到Scripts,然后分别打入pip install pygame和pip install tqdm  如下图

步骤2:输入计算pi的代码(顺带输入一下跟进度条有关的代码):

from random import random
from math import sqrt
from time import clock
from tqdm import tqdm
import time
DARTS=8000000
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="")
    time.sleep((clock())/100)
print("Pi值是{}.".format(pi))
print("运行时间是:{:.5f}s".format(clock()))

  (第二个for循环就是显示进度条的)

(Π的计算原理是根据蒙特卡罗方法计算得来)

然后在cmd下打开你所保存的python代码文件

如图:

可以更改DARTS的大小来精确pi后面的小数位

然后,这个程序就大功告成了!!!

原文地址:https://www.cnblogs.com/asd516970982/p/10568904.html