Python math

Constants, rounding, trigonometry, and the float edge cases that bite in production.

Beginner
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

FunctionMeaningExample
math.sqrt(x)Square rootmath.sqrt(16) -> 4.0
math.pow(x, y)Power, always floatmath.pow(2, 10)
math.log(x, base)Logarithmmath.log(8, 2) -> 3.0
math.log10 / log2Base 10 / 2math.log10(1000)
math.hypot(a, b)Euclidean normmath.hypot(3, 4) -> 5.0
math.factorial(n)n!math.factorial(5) -> 120
math.gcd(a, b)Greatest common divisormath.gcd(12, 18) -> 6
Python
import math

math.degrees(math.pi)      # 180.0
math.radians(180)          # 3.141592653589793
math.sin(math.pi / 2)      # 1.0
math.sqrt(-1) raises ValueError; use cmath.sqrt(-1) for complex results. 0/0 with floats gives ZeroDivisionError, not NaN.

Friends & Partners