基于Python计算圆周率pi代码实例

时间:2021-05-22

一 计算公式:

二 实现代码

(1)

import mathfrom tqdm import tqdmimport timetotal,s,n,t=0.0,1,1.0,1.0while(math.fabs(t)>=1e-6): total+=t n+=2 s=-s t=s/nk=total*4print("π值是{:.10f} 运行时间为{:.4f}秒".format(k,time.clock()))for i in tqdm(range(101)): print("\r{:3}%".format(i),end="") time.sleep(0.1)

(2)

import timeimport 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.0while(math.fabs(t)>=1e-6): total+=t n+=2 s=-s t=s/nk=total*4start = 371for i in range(start + 1): print(index(i, start), end='') time.sleep(0.01)print("\n π值是{:.10f}".format(k))

(3)

import timeimport mathtotal,s,n,t=0.0,1,1.0,1.0while(math.fabs(t)>=1e-6): total+=t n+=2 s=-s t=s/nk=total*4scale=50print("".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))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章