拉马努金公式
def myreduce(m):
value = 1
for i in range(1,m+1):
value = value*i
return value
def sumfun(m):
div = (396**(4*m))*((myreduce(m))**4)
return (26390*m + 1103)*myreduce(4*m)/div
COUNT = 1000
sumvalue = 0
for m in range(0, COUNT+1):
sumvalue += sumfun(m)
temp = 2*(2**0.5)*sumvalue/(99**2)
print('%.4f'%(1/temp))
蒙特卡洛方法
from random import random
COUNT = 1000000
WIDTH = 1
num_in_cir = 0
for i in range(1, COUNT+1):
x = random()
y = random()
if (x**2 + y**2) <= WIDTH:
num_in_cir += 1
pi = 4*(num_in_cir/COUNT)
print('%.4f'%(pi))