The math module in the Python standard library gives you mathematical functions and constants beyond basic arithmetic operators. Reach for it when you need a square root, a logarithm, a trigonometric value, or a constant like pi.
Its functions work on real numbers, meaning integers and floats. For complex numbers, Python provides the separate cmath module with the same function names.
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793The import math line loads the module. math.sqrt(16) returns the square root as a float, while math.pi is a constant rather than a function, so you access it without parentheses.
Mathematical constants
Like every module in the Python standard library, the math module needs no installation, and it ships with several constants for precise numerical work. Each one is a regular float you can use in any calculation.
import math
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
print(math.tau) # 6.283185307179586
print(math.inf) # inf
print(math.nan) # nanHere is what each of these five constants represents and roughly what value it holds.
| Constant | Description |
|---|---|
| math.pi | Ratio of a circle's circumference to its diameter, approximately 3.14159 |
| math.e | Euler's number, the base of the natural logarithm, approximately 2.71828 |
| math.tau | Equal to 2 times pi, approximately 6.28318 |
| math.inf | Floating-point positive infinity |
| math.nan | Floating-point "not a number" value |
Use math.inf and math.nan when you need to represent unbounded values or missing numeric results. You can test for them with math.isinf(x) and math.isnan(x).
Rounding and integer functions
The module provides several ways to convert floats to integers with explicit control over the rounding direction.
import math
print(math.ceil(4.2)) # 5
print(math.floor(4.8)) # 4
print(math.trunc(-3.7)) # -3math.ceil returns the smallest integer greater than or equal to its argument, so 4.2 becomes 5. math.floor goes the other way and returns 4 for 4.8. math.trunc cuts off the decimal part, truncating toward zero, which is why -3.7 becomes -3.
Use ceil when you need to round up, for example to work out how many pages a long document needs. Use floor when you need to round down, such as counting how many full groups you can form from a collection.
Square roots, powers, and absolute values
These functions handle the most common number transformations you will meet in everyday code.
import math
print(math.sqrt(25)) # 5.0
print(math.pow(2, 10)) # 1024.0
print(math.fabs(-42.7)) # 42.7math.sqrt returns the square root as a float. math.pow raises the first argument to the power of the second and always returns a float, and math.fabs returns the absolute value as a float.
For integer powers, the built-in pow function or the ** operator is often more convenient. Use math.pow only when you specifically want the float result.
Logarithms and exponentials
The module handles natural logs, base-10 logs, base-2 logs, and the exponential function.
import math
print(math.log(math.e)) # 1.0
print(math.log10(1000)) # 3.0
print(math.log2(8)) # 3.0
print(math.exp(1)) # 2.718281828459045math.log with one argument returns the natural logarithm, which uses base e. math.log10 and math.log2 cover the two other common bases, and math.exp raises e to the given power.
If you need a logarithm with any other base, pass the base as a second argument. For example, math.log(8, 2) returns 3.0.
Trigonometry
Trigonometric functions expect angles in radians, not degrees. Convert between the two with math.radians and math.degrees.
import math
angle = math.radians(30)
print(math.sin(angle)) # 0.49999999999999994
print(math.cos(angle)) # 0.8660254037844387
print(math.tan(angle)) # 0.5773502691896257math.radians(30) converts 30 degrees to radians before the sin, cos, and tan calls compute their values. The sine of 30 degrees should be exactly 0.5, and the tiny difference you see is normal floating-point rounding.
You can convert a radian result back to degrees with math.degrees, which is handy after calling the inverse trig functions:
import math
print(math.degrees(math.asin(0.5))) # 29.999999999999996math.asin(0.5) returns the arcsine in radians, and math.degrees turns that radian value back into degrees, again with a tiny rounding difference instead of an exact 30.
Float rounding errors and isclose
Floating-point arithmetic produces tiny rounding errors, so checking floats with == often fails even when the values are mathematically equal. The math.isclose function is the reliable alternative.
import math
result = math.sin(math.radians(30))
print(result == 0.5) # False
print(math.isclose(result, 0.5)) # TrueThe direct == check is False because of the rounding error you saw in the trigonometry section. math.isclose returns True because the two values match within a small default relative tolerance.
You can loosen or tighten that tolerance with the rel_tol and abs_tol parameters when the defaults do not fit your problem:
import math
print(math.isclose(100.0, 101.0, rel_tol=0.01)) # TrueThis returns True because the difference of 1.0 falls within the 1 percent relative tolerance. Raising or lowering rel_tol changes how far apart two values can be while still counting as close.
Integer functions: gcd, lcm, comb, perm
The module also covers discrete math, which shows up in probability problems and algorithm work.
import math
print(math.gcd(48, 18)) # 6
print(math.lcm(4, 6)) # 12
print(math.comb(5, 2)) # 10
print(math.perm(5, 2)) # 20math.gcd returns the greatest common divisor and math.lcm returns the least common multiple. math.comb(5, 2) counts the ways to pick 2 items from 5 when order does not matter, while math.perm(5, 2) counts arrangements where order matters.
These four functions replace a lot of hand-written loops in probability calculations, combinatorial problems, and algorithm design.
When to use math vs built-in functions
Python has a few built-in functions that overlap with the math module, and choosing between them mostly comes down to the return type you want.
| Task | Built-in | math module |
|---|---|---|
| Absolute value | abs(-5) | math.fabs(-5), returns float |
| Power | pow(2, 10) or 2 ** 10 | math.pow(2, 10), returns float |
| Rounding | round(4.5), banker's rounding | math.ceil(4.2), math.floor(4.8), explicit direction |
| Sum of iterable | sum([1, 2, 3]) | No equivalent |
| Product of iterable | No built-in | math.prod([1, 2, 3, 4]) |
Use math.ceil and math.floor when you need a specific rounding direction, and the built-in round for general-purpose rounding. Use the ** operator for integer exponentiation, and math.pow or math.sqrt when you explicitly want a float back.
Next steps
The math module is the foundation for numeric work in pure Python. From here, a natural next step is to generate random values with the random module, then look at the statistics module for computing mean, median, and standard deviation on datasets.
Rune AI
Key Insights
- The math module provides mathematical constants like
pi,e, andtau. - Use
math.sqrt,math.ceil,math.floorfor common number operations. - Use
math.log,math.log10,math.log2for logarithms. - Trig functions like
math.sin,math.cos, andmath.tanexpect radians. math.iscloseis the safe way to compare floating-point values.math.gcdandmath.lcmhandle integer divisibility.math.combandmath.permcompute combinations and permutations.
Frequently Asked Questions
Do I need to install the math module?
What is the difference between math.ceil and math.floor?
Can the math module work with complex numbers?
Conclusion
The math module is the starting point for numerical work in pure Python. Learn the constants, rounding functions, and a few of the most useful operations like sqrt, log, and trig functions. When you need more advanced numerical computing, libraries like NumPy build on these same mathematical ideas.
More in this topic
Format Dates and Times in Python
Learn how to use strftime and strptime to format dates as strings and parse date strings into Python datetime objects.
What Is the Python Standard Library?
Learn what the Python standard library is, why it matters, and how to use its built-in modules without installing anything extra.
Encode and Decode Base64 Data in Python
Learn how to use Python's base64 module to encode binary data as text and decode Base64 strings back to bytes.