如何在 Python 中写出 Pi:math.pi、numpy.pi、scipy 等
更新于
如果你只是需要在 Python 中使用 pi,直接用 math.pi 即可。如果你已经在使用 NumPy,那就用 np.pi。它们返回的是同一个双精度值,但对大多数脚本来说,math.pi 是最快、且无需额外依赖的选择。
本指南先从最短可运行语法开始,然后说明在什么情况下更适合使用 math.pi、numpy.pi、scipy.constants.pi、sympy.pi 或 mpmath.pi。
快速答案:如何在 Python 中写出 Pi
import math
math.pi
# 3.141592653589793如果你搜索的是 how to write pi in python,这就是最简洁且正确的答案。下面是常见变体的快速决策表:
| 需求 | 最佳选择 | 原因 |
|---|---|---|
| 不需要额外依赖 | math.pi | 内置于 Python 标准库 |
| NumPy 数组和向量化数学运算 | np.pi | 与 NumPy 操作自然契合 |
| 已经在使用科学常量模块 | scipy.constants.pi | 保持常量导入风格一致 |
| 精确的符号 π | sympy.pi | 符号数学,不是浮点近似值 |
| 需要超过 15 位精度 | mpmath.pi | 任意精度计算 |
Python 中 Pi 常量快速参考
| Method | Code | Value | Install Required? | Best For |
|---|---|---|---|---|
math.pi | import math; math.pi | 3.141592653589793 | No (stdlib) | General use, scripts |
numpy.pi | import numpy as np; np.pi | 3.141592653589793 | Yes (pip install numpy) | Array math, data science |
scipy.constants.pi | from scipy.constants import pi | 3.141592653589793 | Yes (pip install scipy) | Scientific computing |
sympy.pi | import sympy; sympy.pi | Exact symbolic π | Yes (pip install sympy) | Symbolic math, arbitrary precision |
mpmath.pi | import mpmath; mpmath.pi | Arbitrary precision | Yes (pip install mpmath) | 1000+ decimal places |
所有基于浮点数的常量都返回相同的 IEEE 754 双精度值:3.141592653589793(15 位有效数字)。
使用 math.pi(标准库)
math.pi 是在 Python 中使用 pi 最简单的方式。它属于标准库,因此无需安装任何东西。
import math
print(math.pi)
# 3.141592653589793你也可以只导入这个常量:
from math import pi
print(pi)
# 3.141592653589793实用示例:圆的面积和周长
from math import pi
radius = 5
area = pi * radius ** 2
circumference = 2 * pi * radius
print(f"Radius: {radius}")
print(f"Area: {area:.2f}") # 78.54
print(f"Circumference: {circumference:.2f}") # 31.42使用 math.pi 进行三角函数计算
Python 的 math.sin()、math.cos() 和 math.tan() 接受的是弧度,不是角度。使用 math.pi 来转换:
import math
# 90 degrees in radians
angle_rad = math.pi / 2
print(math.sin(angle_rad)) # 1.0
print(math.cos(angle_rad)) # ~0 (6.12e-17 due to floating point)
print(math.tan(math.pi / 4)) # ~1.0
# Convert degrees to radians
degrees = 45
radians = degrees * math.pi / 180 # or use math.radians(45)
print(math.sin(radians)) # 0.7071067811865476使用 numpy.pi(NumPy)
如果你已经在做数值计算并使用 NumPy,那么 np.pi 是很方便的选择。它的值与 math.pi 完全相同。
import numpy as np
print(np.pi)
# 3.141592653589793为什么用 numpy.pi 而不是 math.pi?
当你处理数组时,numpy.pi 更有优势。NumPy 可以把 pi 广播到整个数组,而不需要显式循环:
import numpy as np
# Generate angles from 0 to 2π
angles = np.linspace(0, 2 * np.pi, 8, endpoint=False)
# Compute sine values for all angles at once
sine_values = np.sin(angles)
for angle, sine in zip(angles, sine_values):
print(f"sin({angle:.4f}) = {sine:.4f}")向量化圆计算
import numpy as np
radii = np.array([1, 2, 3, 4, 5])
areas = np.pi * radii ** 2
circumferences = 2 * np.pi * radii
print("Radii:", radii)
print("Areas:", np.round(areas, 2))
print("Circumferences:", np.round(circumferences, 2))使用 scipy.constants.pi
SciPy 提供了 pi 以及其他物理和数学常量。它的值同样是浮点数,但如果你的代码已经因为其他常量而依赖 scipy.constants,那它会很方便。
from scipy.constants import pi, e, golden
print(f"π = {pi}")
print(f"e = {e}")
print(f"φ = {golden}")math.pi vs numpy.pi vs scipy.constants.pi
import math
import numpy as np
from scipy.constants import pi as scipy_pi
print(math.pi == np.pi == scipy_pi) # True这三个返回的都是完全相同的浮点数。下面是各自适用的场景:
| Scenario | Recommended | Reason |
|---|---|---|
| 简单脚本,无需依赖 | math.pi | 标准库,无需安装 |
| NumPy 数组计算 | np.pi | 已经导入,适合数组 |
| 使用 scipy 的科学代码 | scipy.constants.pi | 与其他常量保持一致 |
| 符号数学 / 证明 | sympy.pi | 精确表示,不是浮点数 |
| 需要 1000+ 位 pi | mpmath.pi | 任意精度 |
获取任意精度的 Pi
标准的 math.pi 只提供 15 位小数(IEEE 754 双精度)。如果你需要更多位数——用于研究、基准测试或教学——可以使用 mpmath:
from mpmath import mp
# Set precision to 50 decimal places
mp.dps = 50
print(mp.pi)
# 3.1415926535897932384626433832795028841971693993751
# Set precision to 100 decimal places
mp.dps = 100
print(mp.pi)SymPy 也可以通过 evalf() 支持任意精度:
import sympy
# Get pi to 50 decimal places
print(sympy.pi.evalf(50))
# 3.1415926535897932384626433832795028841971693993751使用 Python 算法计算 Pi
除了使用内置常量之外,你也可以通过程序计算 pi。这对于学习、面试以及理解数值方法都很有帮助。
Leibniz 级数
Leibniz 公式:π/4 = 1 - 1/3 + 1/5 - 1/7 + ...
def leibniz_pi(n_terms: int) -> float:
"""Approximate pi using the Leibniz series."""
pi = 0.0
for i in range(n_terms):
pi += ((-1) ** i) / (2 * i + 1)
return 4 * pi
print(f" 1,000 terms: {leibniz_pi(1_000):.10f}")
print(f"100,000 terms: {leibniz_pi(100_000):.10f}")
print(f" Actual math.pi: {3.141592653589793:.10f}")Leibniz 级数收敛很慢——你大约需要 300,000 项才能得到 5 位正确小数。
蒙特卡洛估计
向正方形中随机投点,并统计落在内切圆中的点数:
import random
def monte_carlo_pi(n_points: int) -> float:
"""Estimate pi using Monte Carlo simulation."""
inside = sum(
1 for _ in range(n_points)
if random.random() ** 2 + random.random() ** 2 <= 1
)
return 4 * inside / n_points
# More points = better estimate
for n in [1_000, 10_000, 100_000, 1_000_000]:
estimate = monte_carlo_pi(n)
error = abs(estimate - 3.141592653589793)
print(f"{n:>10,} points: π ≈ {estimate:.6f} (error: {error:.6f})")Chudnovsky 算法(快速收敛)
Chudnovsky 算法是像 mpmath 这样的库内部使用的方法。每一项大约能增加 14 位数字:
from decimal import Decimal, getcontext
def chudnovsky_pi(precision: int) -> Decimal:
"""Calculate pi using the Chudnovsky algorithm."""
getcontext().prec = precision + 10
C = 426880 * Decimal(10005).sqrt()
K, M, X, L, S = 6, 1, 1, 13591409, 13591409
for i in range(1, precision):
M = M * (K ** 3 - 16 * K) // ((i) ** 3)
K += 12
L += 545140134
X *= -262537412640768000
S += Decimal(M * L) / X
return C / S
pi = chudnovsky_pi(50)
print(f"Chudnovsky: {pi}")使用 Pi 时的常见错误
1. 角度与弧度混淆
import math
# WRONG: passing degrees directly
print(math.sin(90)) # 0.8939... (not 1.0!)
# CORRECT: convert to radians first
print(math.sin(math.pi/2)) # 1.0
print(math.sin(math.radians(90))) # 1.02. 浮点精度问题
import math
# This is NOT exactly zero due to floating-point arithmetic
result = math.cos(math.pi / 2)
print(result) # 6.123233995736766e-17
print(result == 0) # False
# Use math.isclose() for comparisons
print(math.isclose(result, 0, abs_tol=1e-9)) # True3. 手动定义 Pi
# DON'T: lose precision with manual constants
pi = 3.14
area = pi * 10 ** 2 # 314.0 (inaccurate)
# DO: use math.pi for full precision
import math
area = math.pi * 10 ** 2 # 314.1592653589793实际应用
球体体积和表面积
import math
def sphere_volume(radius: float) -> float:
return (4/3) * math.pi * radius ** 3
def sphere_surface_area(radius: float) -> float:
return 4 * math.pi * radius ** 2
r = 7
print(f"Sphere (r={r}): volume = {sphere_volume(r):.2f}, surface area = {sphere_surface_area(r):.2f}")极坐标到笛卡尔坐标转换
import math
def polar_to_cartesian(r: float, theta_degrees: float) -> tuple:
"""Convert polar coordinates (r, θ°) to cartesian (x, y)."""
theta_rad = math.radians(theta_degrees)
x = r * math.cos(theta_rad)
y = r * math.sin(theta_rad)
return round(x, 6), round(y, 6)
# Example: point at distance 5, angle 60°
print(polar_to_cartesian(5, 60)) # (2.5, 4.330127)
print(polar_to_cartesian(10, 45)) # (7.071068, 7.071068)摆的周期
import math
def pendulum_period(length_m: float, g: float = 9.81) -> float:
"""Calculate the period of a simple pendulum in seconds."""
return 2 * math.pi * math.sqrt(length_m / g)
print(f"1m pendulum: {pendulum_period(1):.3f} seconds") # ~2.006s用 Python 可视化 Pi
如果你正在使用数据科学工具,可以轻松可视化与 pi 相关的函数:
import numpy as np
# Generate sine wave data
x = np.linspace(0, 4 * np.pi, 200)
y_sin = np.sin(x)
y_cos = np.cos(x)Tip: 通过 PyGWalker (opens in a new tab) 可以立即将你的 NumPy 数据转化为交互式可视化。导入 DataFrame 后,PyGWalker 会在 Jupyter Notebook 中直接提供类似 Tableau 的拖拽式界面——无需额外代码。
常见问题
不导入任何东西,如何在 Python 中获取 pi?
你可以在不导入任何模块的情况下近似 pi,但这不适合生产代码:
pi_approx = 355 / 113 # 3.1415929... (accurate to 6 decimal places)
# Or use: 22/7 = 3.142857... (only 2 decimal places)对于准确计算,请始终优先使用 math.pi。
math.pi 和 numpy.pi 一样吗?
是的。两者返回的都是相同的 IEEE 754 双精度浮点数:3.141592653589793。如果不需要 NumPy,就用 math.pi;如果你已经在使用 NumPy 数组,就用 np.pi。
Python 会存储多少位 pi?
标准的 math.pi 存储 15 位有效十进制数字(IEEE 754 双精度)。如果你需要更多位数,可以使用 mpmath:
from mpmath import mp
mp.dps = 1000 # 1000 decimal places
print(mp.pi)如何在 Python 中把角度转换为弧度?
使用 math.radians(),或者乘以 math.pi / 180:
import math
radians = math.radians(90) # 1.5707963267948966
radians = 90 * math.pi / 180 # same result不导入 math 也能在 Python 中使用 pi 吗?
可以——使用 numpy.pi、scipy.constants.pi 或 sympy.pi。但如果你希望零依赖,math.pi 是最好的选择,因为 math 属于标准库,无需安装。
相关文章
- Python Map Function -- 使用 map() 在序列中应用 math.pi 变换
- Python Generators -- 为大规模计算惰性生成 pi 数字序列
- NumPy Linspace -- 使用 np.pi 创建等间距数组,用于三角函数绘图