Python Math Module
Python 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.
Common Functions and Constants
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
Combinatorics and Integer Helpers
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.
Common Mistakes to Avoid
- Passing negative numbers to
math.sqrt(): Taking the square root of-1raisesValueError: math domain error; usecmath.sqrt(-1)if you need complex results. - Using
math.floor()when you want integer truncation on negatives:math.floor(-2.3)returns-3, whilemath.trunc(-2.3)returns-2. - Comparing floats with
==instead ofmath.isclose(): Binary float rounding makes(0.1 + 0.2) == 0.3evaluate toFalse.
Frequently Asked Questions
What is the difference between math.floor() and int() on negative numbers?
math.floor(-3.7) rounds toward negative infinity (-4), while int(-3.7) truncates toward zero (-3).
How do I convert degrees to radians for math.sin() and math.cos()?
Pass degrees through math.radians(90) first, because all trigonometric functions in math expect radians.
Does 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.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.