一、计算圆周率pi的方法
(一)公式法
pi=0
N=eval(input())
for k in range(N):
pi+=1/pow(16,k)*(4/(8*k+1)-2/(8*k+4)-1/(8*k+5)-1/(8*k+6))
print(pi)
(二)蒙特卡罗方法
#e.6.1(p115)
from random import random
from math import sqrt
from time import perf_counter
DARTS = 100000000
hits = 0.0
perf_counter()
for i in range(1, DARTS+1):
x, y = random(), random()
dist = sqrt(x ** 2 + y ** 2)
if dist <= 1.0:
hits = hits + 1
pi = 4 * (hits/DARTS)
print("Pi值是{}.".format(pi))
print("运行时间是: {:5.5}s".format(perf_counter()))
二、用进度条显示算的进度
from random import random
from math import sqrt
from time import *
DARTS=100000000
hits=0.0
n=1
perf_counter()
for i in range(1,DARTS+1):
x,y=random(),random()
dist=sqrt(x**2+y**2)
if dist <=1.0:
hits=hits+1
if i == DARTS * 0.01 *n:
print("\r{}%[{}->]".format(n,'*'*n),end='')
n += 1
pi=4*(hits/DARTS)
print("\npi的值为:{}.".format(pi))
print("运行时间为:{:.5f}s.".format(perf_counter()))
print('(2021310143103)')
代码运行截图:
三、算圆周率pi的具体公式
for k in range(N):
pi+=1/pow(16,k)*(4/(8*k+1)-2/(8*k+4)-1/(8*k+5)-1/(8*k+6))
标签:hits,Python,圆周率,random,DARTS,print,import,pi From: https://www.cnblogs.com/gzygshyq/p/17796841.html