用python计算圆周率PI

1.蒙特卡洛求圆周率

向区域内随即撒点

当点的数目足够多时,落在圆的点数目与在正方形点数目成正比

即圆的面积和正方形的面积成正比

可以得出计算圆周率的算法

  1. DARTS=100000000  
  2. hits=0.0  
  3. clock()  
  4. for i in range(1,DARTS+1):  
  5.     x,y=random(),random()  
  6.     dist=sqrt(x**2+y**2)  
  7.     if dist <=1.0:  
  8.         hits=hits+1  
  9. pi=4*(hits/DARTS)  

2.安装tqdm来表示计算进度

在命令指令符中输入pip install tqdm来安装

 

3.计算圆周率与tqdm一起编码

  1. from random import random  
  2. from math import sqrt  
  3. from time import *  
  4. from tqdm import tqdm  
  5. DARTS=100000000  
  6. hits=0.0  
  7. clock()  
  8. for i in range(1,DARTS+1):  
  9.     x,y=random(),random()  
  10.     dist=sqrt(x**2+y**2)  
  11.     if dist <=1.0:  
  12.         hits=hits+1  
  13. pi=4*(hits/DARTS)  
  14. for i in tqdm(range(10)):  
  15.     print("\r{:3}%\n".format(i/10*100),end="") #这里的i/10*100指每10%显示一次  
  16.     sleep((clock())/100)#用执行程序的总时间来算出进度条间隔的时间    
  17. print("pi的值{}.".format(pi))  
  18. print("运行时间:{:.5f}s".format(clock()))  

 

4.运行该程序,得出结果

 

猜你喜欢

转载自www.cnblogs.com/z2273533704/p/10568782.html