python头歌作业计算圆周率
时间: 2025-05-16 09:09:11 浏览: 34
### 使用Python计算圆周率
可以通过多种方法来实现 Python 中的圆周率 π 的计算。以下是基于 Chudnovsky 算法以及 Monte Carlo 方法和级数展开的方法。
#### 基于 Chudnovsky 算法
Chudnovsky 算法是一种高效的高精度圆周率计算方法,其核心公式如下:
\[
\frac{1}{\pi} = 12 \sum_{k=0}^\infty \frac{(-1)^k (6k)! (13591409 + 545140134k)}{(3k)!(k!)^3 640320^{3k + 3/2}}
\]
下面是一个使用 `decimal` 模块实现该算法的例子[^1]:
```python
from decimal import Decimal, getcontext
def compute_pi(chudnovsky_iterations):
getcontext().prec = chudnovsky_iterations * 14 # 设置精度
C = 426880 * Decimal(10005).sqrt()
M = 1
L = 13591409
X = 1
K = 6
S = L
for i in range(1, chudnovsky_iterations):
M = (K ** 3 - 16 * K) * M // i ** 3
L += 545140134
X *= -262537412640768000
S += Decimal(M * L) / X
pi = C / S
return str(pi)[:chudnovsky_iterations]
print(compute_pi(10))
```
此代码利用了大整数运算,并通过调整迭代次数控制精度。
---
#### 基于 Monte Carlo 方法
Monte Carlo 方法是一种统计学上的近似方法,它通过随机采样估算圆周率。具体原理是在单位正方形内均匀分布点,并判断这些点是否落在四分之一圆内部[^3]。
下面是其实现代码[^4]:
```python
import random
from time import perf_counter
DARTS = 1000000 # 投掷次数
hits = 0
start = perf_counter()
for _ in range(DARTS):
x, y = random.random(), random.random()
distance = pow(x**2 + y**2, 0.5)
if distance <= 1.0:
hits += 1
pi_estimate = 4 * (hits / DARTS)
end_time = perf_counter() - start
print(f"圆周率值是: {pi_estimate}")
print(f"运行时间是: {end_time:.5f}s")
```
这种方法简单易懂,但收敛速度较慢,适合用于教学演示而非高精度需求场景。
---
#### 基于无穷级数
一种经典的级数展开方式是莱布尼茨级数,尽管它的收敛速度很慢,但对于理解基本概念很有帮助。
```python
def calculate_pi_with_series(iterations):
pi_approximation = 0
for k in range(iterations):
term = (-1)**k / (2*k + 1)
pi_approximation += term
return 4 * pi_approximation
print(calculate_pi_with_series(1000000))
```
另一种更快速的方式是基于 Ramanujan 或 Machin 类型的公式,它们能够显著提高效率。
---
### 总结
上述三种方法各有优劣:Chudnovsky 算法适用于极高精度的需求;Monte Carlo 方法直观但低效;而级数展开则适合作为入门学习工具。
阅读全文
相关推荐



















