math Module: Roots, Rounding, Constants, and isclose()Python's math standard library module provides C-backed mathematical functions for real numbers, including square roots, ceilings, floors, logarithms, and trigonometry. Unlike built-ins like abs() or round(), you must write import math before calling them.
All functions in math work with integers and floats; for complex numbers (3 + 4j), use the companion cmath module instead.
Use math.ceil() to always round up, math.floor() to always round down, math.sqrt() for square roots, and math.isclose() to compare floats safely.
import math
pages = math.ceil(43 / 10) # 5 pages for 43 items (10 per page)
bucket = math.floor(7.9) # 7
diagonal = math.sqrt(3**2 + 4**2) # 5.0
circle_area = math.pi * (5 ** 2)
print(pages, bucket, diagonal, round(circle_area, 2))
print(math.isclose(0.1 + 0.2, 0.3)) # True
Python 3.8+ also includes fast integer functions inside math such as math.gcd(a, b) (greatest common divisor), math.lcm(a, b), math.factorial(n), and math.comb(n, k) for combinations.
math.sqrt(): Taking the square root of -1 raises ValueError: math domain error; use cmath.sqrt(-1) if you need complex results.math.floor() when you want integer truncation on negatives: math.floor(-2.3) returns -3, while math.trunc(-2.3) returns -2.== instead of math.isclose(): Binary float rounding makes (0.1 + 0.2) == 0.3 evaluate to False.math.floor() and int() on negative numbers?math.floor(-3.7) rounds toward negative infinity (-4), while int(-3.7) truncates toward zero (-3).
math.sin() and math.cos()?Pass degrees through math.radians(90) first, because all trigonometric functions in math expect radians.
math.fsum() improve accuracy over built-in sum()?Yes. math.fsum(floats) tracks partial sums carefully to avoid precision drift when adding long lists of floats.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.