Python `math` Module Explained

Learn how to use the Python math module for square roots, rounding, trigonometry, logarithms, and mathematical constants.

7 min read

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.

pythonpython
import math
 
print(math.sqrt(16))  # 4.0
print(math.pi)        # 3.141592653589793

The 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.

pythonpython
import math
 
print(math.pi)   # 3.141592653589793
print(math.e)    # 2.718281828459045
print(math.tau)  # 6.283185307179586
print(math.inf)  # inf
print(math.nan)  # nan

Here is what each of these five constants represents and roughly what value it holds.

ConstantDescription
math.piRatio of a circle's circumference to its diameter, approximately 3.14159
math.eEuler's number, the base of the natural logarithm, approximately 2.71828
math.tauEqual to 2 times pi, approximately 6.28318
math.infFloating-point positive infinity
math.nanFloating-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.

pythonpython
import math
 
print(math.ceil(4.2))    # 5
print(math.floor(4.8))   # 4
print(math.trunc(-3.7))  # -3

math.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.

pythonpython
import math
 
print(math.sqrt(25))     # 5.0
print(math.pow(2, 10))   # 1024.0
print(math.fabs(-42.7))  # 42.7

math.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.

pythonpython
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.718281828459045

math.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.

pythonpython
import math
 
angle = math.radians(30)
 
print(math.sin(angle))  # 0.49999999999999994
print(math.cos(angle))  # 0.8660254037844387
print(math.tan(angle))  # 0.5773502691896257

math.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:

pythonpython
import math
 
print(math.degrees(math.asin(0.5)))  # 29.999999999999996

math.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.

pythonpython
import math
 
result = math.sin(math.radians(30))
print(result == 0.5)              # False
print(math.isclose(result, 0.5))  # True

The 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:

pythonpython
import math
 
print(math.isclose(100.0, 101.0, rel_tol=0.01))  # True

This 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.

pythonpython
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))   # 20

math.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.

TaskBuilt-inmath module
Absolute valueabs(-5)math.fabs(-5), returns float
Powerpow(2, 10) or 2 ** 10math.pow(2, 10), returns float
Roundinground(4.5), banker's roundingmath.ceil(4.2), math.floor(4.8), explicit direction
Sum of iterablesum([1, 2, 3])No equivalent
Product of iterableNo built-inmath.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

Rune AI

Key Insights

  • The math module provides mathematical constants like pi, e, and tau.
  • Use math.sqrt, math.ceil, math.floor for common number operations.
  • Use math.log, math.log10, math.log2 for logarithms.
  • Trig functions like math.sin, math.cos, and math.tan expect radians.
  • math.isclose is the safe way to compare floating-point values.
  • math.gcd and math.lcm handle integer divisibility.
  • math.comb and math.perm compute combinations and permutations.
RunePowered by Rune AI

Frequently Asked Questions

Do I need to install the math module?

No. The math module is part of the Python standard library and is available in every Python installation. Just use `import math`.

What is the difference between math.ceil and math.floor?

`math.ceil(x)` returns the smallest integer greater than or equal to x (rounds up). `math.floor(x)` returns the largest integer less than or equal to x (rounds down). For positive numbers, ceil rounds up and floor truncates toward zero.

Can the math module work with complex numbers?

No. The math module works with real numbers (integers and floats). For complex numbers, use the `cmath` module instead, which provides the same function names but handles complex inputs.

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.