Python math
Constants, rounding, trigonometry, and the float edge cases that bite in production.
Key PointsUse `math.isclose` instead of `==` for floats, and remember `math.floor` rounds down while `int()` truncates toward zero.
Constants and Rounding
Python
import math
math.pi, math.e, math.tau # 3.14159 2.71828 6.28318
math.inf, -math.inf, math.nan
math.floor(3.7), math.ceil(3.2), round(3.5)
# 3 4 4
math.floor(-3.2), int(-3.2)
# -4 -3 —— floor 向下,int 向零Comparison and Precision
Python
import math
math.isclose(0.1 + 0.2, 0.3) # True
math.isclose(1e-10, 0, abs_tol=1e-9) # True,绝对容差
math.isnan(math.nan) # True
math.nan == math.nan # False —— NaN 不等于自身
# 金额别用 float
from decimal import Decimal
Decimal("0.1") + Decimal("0.2") # Decimal('0.3')Powers, Logs, Trigonometry
| Function | Meaning | Example |
|---|---|---|
| math.sqrt(x) | Square root | math.sqrt(16) -> 4.0 |
| math.pow(x, y) | Power, always float | math.pow(2, 10) |
| math.log(x, base) | Logarithm | math.log(8, 2) -> 3.0 |
| math.log10 / log2 | Base 10 / 2 | math.log10(1000) |
| math.hypot(a, b) | Euclidean norm | math.hypot(3, 4) -> 5.0 |
| math.factorial(n) | n! | math.factorial(5) -> 120 |
| math.gcd(a, b) | Greatest common divisor | math.gcd(12, 18) -> 6 |
Python
import math
math.degrees(math.pi) # 180.0
math.radians(180) # 3.141592653589793
math.sin(math.pi / 2) # 1.0math.sqrt(-1) raises ValueError; use cmath.sqrt(-1) for complex results. 0/0 with floats gives ZeroDivisionError, not NaN.常量与取整
Python
import math
math.pi, math.e, math.tau # 3.14159 2.71828 6.28318
math.inf, -math.inf, math.nan
math.floor(3.7), math.ceil(3.2), round(3.5)
# 3 4 4
math.floor(-3.2), int(-3.2)
# -4 -3 —— floor 向下,int 向零比较与精度
Python
import math
math.isclose(0.1 + 0.2, 0.3) # True
math.isclose(1e-10, 0, abs_tol=1e-9) # True,绝对容差
math.isnan(math.nan) # True
math.nan == math.nan # False —— NaN 不等于自身
# 金额别用 float
from decimal import Decimal
Decimal("0.1") + Decimal("0.2") # Decimal('0.3')幂、对数与三角
| 函数 | 含义 | 示例 |
|---|---|---|
| math.sqrt(x) | 平方根 | math.sqrt(16) -> 4.0 |
| math.pow(x, y) | 幂,总返回 float | math.pow(2, 10) |
| math.log(x, base) | 对数 | math.log(8, 2) -> 3.0 |
| math.log10 / log2 | 以 10 / 2 为底 | math.log10(1000) |
| math.hypot(a, b) | 欧氏范数 | math.hypot(3, 4) -> 5.0 |
| math.factorial(n) | 阶乘 | math.factorial(5) -> 120 |
| math.gcd(a, b) | 最大公约数 | math.gcd(12, 18) -> 6 |
Python
import math
math.degrees(math.pi) # 180.0
math.radians(180) # 3.141592653589793
math.sin(math.pi / 2) # 1.0math.sqrt(-1) 抛 ValueError;要复数结果用 cmath.sqrt(-1)。浮点 0/0 抛的是 ZeroDivisionError,不是 NaN。