代码语言:python代码运行次数:0复制
def pi_01():
pi, N=0, 100
func = lambda i: 1/pow(16,i)*(4/(8*i 1)- 2/(8*i 4)-1/(8*i 5)-1/(8*i 6))
for i in range(N): pi =func(i)
print(pi)
import random, time
def pi_02():
N, k =1000*1000, 0
start=time.perf_counter()
for i in range(N):
x,y = random.random(),random.random()
dist = pow(x**2 y**2,0.5)
if dist <= 1.0: k =1
pi=4*(k/N)
print("pi={},run time={:.2f}s".format(pi,time.perf_counter()-start))
# pi = pi * Decimal(12)/Decimal(640320**Decimal(1.5))
def pi_03():
from decimal import Decimal, getcontext
getcontext().prec=100
print(sum(1/Decimal(16)**k *
(Decimal(4)/(8*k 1) -
Decimal(2)/(8*k 4) -
Decimal(1)/(8*k 5) -
Decimal(1)/(8*k 6)) for k in range(100)))
if __name__ == "__main__":
pi_01()
pi_02()
pi_03()
3.141592653589793
pi=3.13904 , run time=0.77s
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117070
[Finished in 0.9s]
https://www.zhihu.com/question/20756479