在Python中,计算圆周率(π)可以通过多种方法实现,下面是一些常见的方法:
BBP公式法
from math import log, sqrt
def approximate_pi_bbp(places=10):
pi = 0
n = 1
while True:
term = (-1) n / (2 * n + 1)
pi += term * log(16) / log(4)
pi = pi / n
if abs(pi * 4 - 3) < 10 (-places):
break
n += 1
return pi * 4
print(approximate_pi_bbp(places))
蒙特卡罗方法
import random
import time
from tqdm import tqdm
def estimate_pi_montecarlo(num_samples):
inside_circle = 0
for _ in range(num_samples):
x, y = random.random(), random.random()
if x2 + y2 <= 1:
inside_circle += 1
return 4 * inside_circle / num_samples
DARTS =
hits = 0.0
start = time.perf_counter()
for _ in tqdm(range(DARTS)):
x, y = random.random(), random.random()
if x2 + y2 <= 1.0:
hits += 1
pi = 4 * (hits / DARTS)
print("圆周率值是: {:.10f}, 运行时间是: {:.5f}s".format(pi, time.perf_counter() - start))
```
逼近法
import math
def approximate_pi_approximation(n):
return 4 * sum(1 / (2 * i + 1) for i in range(n))
for n in [3, 4, 5, 10, 100, 1000, 10000, ]:
print(n, "-->", approximate_pi_approximation(n))
使用math库
import math
print("Python中的π是:", math.pi)
以上方法都可以用来计算圆周率,其中蒙特卡罗方法通过随机采样来估计π的值,而其他方法则基于数学公式。你可以根据需要的精度选择合适的方法。
如果你需要更精确的计算,并且想要看到计算进度,可以使用`tqdm`库来显示进度条。