import math
defbbp_pi(digits):
pi =0for k inrange(digits):
term =(1/16**k)*((4/(8* k +1))-(2/(8* k +4))-(1/(8* k +5))-(1/(8* k +6)))
pi += term
return pi
# 指定所需的小数位数
decimal_places =100
calculated_pi = bbp_pi(decimal_places)print("计算得到的π值:", calculated_pi)
运行结果
计算得到的π值: 3.141592653589793
请按任意键继续. . .
3. 蒙特卡洛方法计算π
原理
代码
from random import random
from math import sqrt
from time import clock
DARTS =1000# 一共投掷的点数
hits =0.0# 范围内的点数
clock()计时
for i inrange(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(clock()))