基于Python计算圆周率pi代码实例
更新时间:2020年03月25日 11:17:22 作者:Jessie-
这篇文章主要介绍了基于Python计算圆周率pi代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
一 计算公式:

二 实现代码
(1)
import math
from tqdm import tqdm
import time
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
print("π值是{:.10f} 运行时间为{:.4f}秒".format(k,time.clock()))
for i in tqdm(range(101)):
print("\r{:3}%".format(i),end="")
time.sleep(0.1)
(2)
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))
(3)
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))
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Python发送form-data请求及拼接form-data内容的方法
这篇文章主要介绍了Python发送form-data请求及拼接form-data内容的方法,文中采用的是requests的方式发送multipart/form-data请求,需要的朋友可以参考下2016-03-03
Django-rest-framework中过滤器的定制实例
这篇文章主要介绍了Django-rest-framework中过滤器的定制实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-04-04
Python函数参数匹配模型通用规则keyword-only参数详解
Python3对函数参数的排序规则更加通用化了,即Python3 keyword-only参数,该参数即为必须只按照关键字传递而不会有一个位置参数来填充的参数。这篇文章主要介绍了Python函数参数匹配模型通用规则keyword-only参数,需要的朋友可以参考下2019-06-06


最新评论