math wraps the C standard library's math functions, covering square roots, trigonometric functions like sin/cos/tan, logarithms, rounding functions like floor/ceil/trunc, and constants like pi and e. It only operates on plain Python floats and ints, not complex numbers, since a separate cmath module handles those, and functions like math.sqrt raise a ValueError for invalid input, like a negative number, rather than silently returning something unexpected like nan.
1Understanding math Module
math wraps the C standard library's math functions, covering square roots, trigonometric functions like sin/cos/tan, logarithms, rounding functions like floor/ceil/trunc, and constants like pi and e. It only operates on plain Python floats and ints, not complex numbers, since a separate cmath module handles those, and functions like math.sqrt raise a ValueError for invalid input, like a negative number, rather than silently returning something unexpected like nan.
Use math.isclose(a, b) for float comparisons instead of ==, and math.floor()/math.ceil() when you specifically need rounding toward negative or positive infinity rather than round()'s round-half-to-even behavior.
import math
print(math.sqrt(16))
print(math.floor(3.7))
print(math.ceil(3.2))2Practical Example
Here is a real-world application of math Module showing how it is used in production Python code.
import math
radius = 5
area = math.pi * radius ** 2
print(round(area, 2))3Best Practices
Follow these guidelines when working with math Module:
1. Use math functions instead of hand-rolling equivalents, like a manual square-root approximation, since they're implemented in C and both faster and more numerically correct
2. Reach for cmath instead of math when working with complex numbers, since math functions reject them
3. Use math.isclose() rather than == for comparing computed floating-point results
Tip: Use math.isclose(a, b) for float comparisons instead of ==, and math.floor()/math.ceil() when you specifically need rounding toward negative or positive infinity rather than round()'s round-half-to-even behavior.
import math
print(math.sqrt(16))
print(math.floor(3.7))
print(math.ceil(3.2))