用python计算圆周率PI,并显示进度条

发布时间 2023-11-13 19:46:48作者: 伊蕾娜。

用python计算圆周率PI

‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬描述

用python计算圆周率PI‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬

‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬1.要求能算到小数点后面越多越好(5分)‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬

‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬2.并用进度条提示算的进度,能给出多种进度条越好(5分)‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬

‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪3.要求给出算圆周率Pi具体公式或者算法说明

 

一、具体公式:

莱布尼茨公式

π/4=1-1/3+1/5-1/7+1/9-1/11+……

蒙特卡罗法(打鸟法)

一个正方形内部相切一个圆,圆和正方形的面积之比是π/4。 
在这个正方形内部,随机产生n个点(这些点服从均匀分布),计算它们与中心点的距离是否大于圆的半径,以此判断是否落在圆的内部。

统计圆内的点数,与n的比值乘以4,就是π的值。理论上,n越大,计算的π值越准。

二、代码如下:

(1)、蒙特卡罗法(打鸟法)

import math
import time
scale=10
print("执行开始")
t=time.process_time()
for i in range(scale+1):
    a,b='**'*i,'..'*(scale-i)
    c=(i/scale)*100
    π=4*(4*math.atan(1/5)-math.atan(1/239))
    print("[{:3}{}->{}%]".format(a,b,c))
    time.sleep(0.1)
print("π =",format(π))
print("运行时间:{:.2f}s".format(t))
print("执行结束")

 

运行结果如下:

 

(2)、莱布尼兹公式

import time
import math
total,s,n,t=0.0,1,1.0,1.0
while(math.fabs(t)>=1e-6):
    total+=t
    n+=2
    s=-s
    t=s/n
k=total*4
scale=50
print("".center(scale//2,"-"))
start = time.perf_counter()
for i in range(scale+1):
    a="*"*i
    b="."*(scale-i)
    c=(i/scale)*100
    d=time.perf_counter() - start
    print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,d),end='')
    time.sleep(0.1)
print("\n π值是{:.10f}".format(k))

 

运行结果如下:

 

(3)、莱布尼兹公式

import time
import math
  
  
class Index(object):
    def __init__(self, number=50, decimal=2):
        self.decimal = decimal
        self.number = number
        self.a = 100/number  
  
    def __call__(self, now, total):
        percentage = self.percentage_number(now, total)
        well_num = int(percentage / self.a)
        progress_bar_num = self.progress_bar(well_num)
        result = "\r%s %s" % (progress_bar_num, percentage)
        return result
  
    def percentage_number(self, now, total):
        return round(now / total * 100, self.decimal)
  
    def progress_bar(self, num):
        well_num = "#" * num
        space_num = " " * (self.number - num)
        return '[%s%s]' % (well_num, space_num)
  
  
  
index = Index()
 
 
total,s,n,t=0.0,1,1.0,1.0
while(math.fabs(t)>=1e-6):
    total+=t
    n+=2
    s=-s
    t=s/n
k=total*4
  
start = 371
for i in range(start + 1):
    print(index(i, start), end='')
    time.sleep(0.01)
     
     
print("\n π值是{:.10f}".format(k))

 

运行结果如下: