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

脚本专栏 发布日期:2024/10/22 浏览次数:1

正在浏览:基于Python计算圆周率pi代码实例

一 计算公式:

基于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))

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

一文看懂荣耀MagicBook Pro 16
荣耀猎人回归!七大亮点看懂不只是轻薄本,更是游戏本的MagicBook Pro 16.
人们对于笔记本电脑有一个固有印象:要么轻薄但性能一般,要么性能强劲但笨重臃肿。然而,今年荣耀新推出的MagicBook Pro 16刷新了人们的认知——发布会上,荣耀宣布猎人游戏本正式回归,称其继承了荣耀 HUNTER 基因,并自信地为其打出“轻薄本,更是游戏本”的口号。
众所周知,寻求轻薄本的用户普遍更看重便携性、外观造型、静谧性和打字办公等用机体验,而寻求游戏本的用户则普遍更看重硬件配置、性能释放等硬核指标。把两个看似难以相干的产品融合到一起,我们不禁对它产生了强烈的好奇:作为代表荣耀猎人游戏本的跨界新物种,它究竟做了哪些平衡以兼顾不同人群的各类需求呢?