Math Module

Python Modules

Python math Module

In this tutorial, we'll use the math module for common jobs such as square roots, rounding, distances, powers, and trigonometry.

Python's math module provides efficient mathematical functions and constants for real numbers. It covers roots, powers, logarithms, trigonometry, combinatorics, and several tools that are more accurate or expressive than handwritten calculations.

It is part of the standard library:

import math

Constants

The best-known constants are π and e:

import math

print(math.pi)
print(math.e)
print(math.tau)

Use math.pi instead of typing a short approximation:

import math


def circle_area(radius):
    return math.pi * radius ** 2


print(circle_area(3))

math.inf represents positive infinity and math.nan represents “not a number”. These special float values require careful comparisons:

value = math.nan

print(math.isnan(value))
print(value == math.nan)
True
False

Use math.isnan() and math.isinf() rather than equality checks.

Square roots, integer roots, and powers

Calculate a square root with sqrt():

import math

print(math.sqrt(81))
9.0

For a non-negative integer, isqrt() returns the integer square root without converting through a float:

print(math.isqrt(80))
print(math.isqrt(81))
8
9

It rounds down and is useful for integer algorithms.

Python's ** operator handles ordinary powers. math.pow() converts its arguments to floats:

print(2 ** 10)
print(math.pow(2, 10))
1024
1024.0

Prefer ** when exact integer results matter.

Distances with hypot

math.hypot() calculates Euclidean distance without manually squaring and adding:

import math

distance = math.hypot(3, 4)
print(distance)
5.0

It accepts more than two coordinates:

length = math.hypot(2, 3, 6)
print(length)

To find the distance between points, pass their coordinate differences:

def distance(point_a, point_b):
    dx = point_b[0] - point_a[0]
    dy = point_b[1] - point_a[1]
    return math.hypot(dx, dy)

Floor, ceiling, and truncation

These functions remove a fractional part in different ways:

import math

value = -2.7

print(math.floor(value))
print(math.ceil(value))
print(math.trunc(value))
-3
-2
-2
  • floor() moves down toward negative infinity.
  • ceil() moves up toward positive infinity.
  • trunc() moves toward zero.

This distinction matters for negative numbers.

A common use for ceil() is calculating how many containers are required:

def pages_required(item_count, page_size):
    if page_size <= 0:
        raise ValueError("page_size must be positive")
    return math.ceil(item_count / page_size)

Accurate sums and products

sum() is appropriate for most everyday calculations. math.fsum() reduces accumulated floating-point rounding error:

import math

values = [0.1] * 10

print(sum(values))
print(math.fsum(values))

Typical output:

0.9999999999999999
1.0

Multiply an iterable with math.prod():

dimensions = [3, 4, 5]
volume = math.prod(dimensions)

print(volume)
60

The product of an empty iterable is 1, matching the mathematical multiplicative identity.

Comparing floating-point results

Many decimal fractions cannot be represented exactly as binary floats:

print(0.1 + 0.2 == 0.3)
False

Use math.isclose() when an approximate comparison is appropriate:

import math

result = 0.1 + 0.2

print(math.isclose(result, 0.3))

For values close to zero, specify an absolute tolerance:

print(math.isclose(0.0000001, 0.0, abs_tol=0.000001))

Choose tolerances based on the problem. A tolerance that is too generous can hide genuine errors.

Greatest common divisor and least common multiple

import math

print(math.gcd(24, 36))
print(math.lcm(6, 8))
12
24

These functions accept multiple integer arguments:

print(math.gcd(24, 36, 60))

Factorials, combinations, and permutations

factorial(n) calculates n × (n - 1) × ... × 1:

import math

print(math.factorial(5))
120

For selections from n items:

print(math.comb(10, 3))
print(math.perm(10, 3))
  • comb() counts selections where order does not matter.
  • perm() counts arrangements where order matters.

These functions expect non-negative integers and return exact integers.

Exponentials and logarithms

import math

print(math.exp(1))
print(math.log(math.e))
print(math.log10(1000))
print(math.log2(1024))
2.718281828459045
1.0
3.0
10.0

math.log(x) uses base e by default. It also accepts a base:

print(math.log(81, 3))

Floating-point rounding means this may be extremely close to an integer rather than mathematically exact. Use isclose() where appropriate.

Logarithms require a positive input. Invalid domains raise ValueError.

Trigonometry and angles

Python's trigonometric functions use radians:

import math

angle = math.radians(30)

print(math.sin(angle))
print(math.cos(angle))
print(math.tan(angle))

Convert in either direction:

print(math.radians(180))
print(math.degrees(math.pi))
3.141592653589793
180.0

Forgetting the degrees-to-radians conversion is one of the most common trigonometry mistakes in programs.

Domain errors and complex numbers

Functions in math operate on real numbers:

math.sqrt(-1)

This raises ValueError. If your problem genuinely uses complex numbers, use cmath:

import cmath

print(cmath.sqrt(-1))
1j

A practical example: loan-free compound growth

import math


def compound_growth(principal, annual_rate, years, periods_per_year=12):
    if principal < 0:
        raise ValueError("principal cannot be negative")
    if periods_per_year <= 0:
        raise ValueError("periods_per_year must be positive")

    periods = years * periods_per_year
    rate_per_period = annual_rate / periods_per_year
    return principal * math.pow(1 + rate_per_period, periods)


future_value = compound_growth(1000, 0.05, 3)
print(f"{future_value:.2f}")

For real financial calculations, binary floating-point may not provide the required monetary rounding rules. Consider decimal.Decimal and the relevant financial specification.

Common math mistakes

  • Typing a rough value for π instead of using math.pi.
  • Forgetting that trigonometric functions expect radians.
  • Assuming floor() and trunc() behave identically for negative values.
  • Comparing calculated floats with exact equality.
  • Using math.pow() when an exact integer power is required.
  • Calling a function outside its mathematical domain.
  • Using floats for money without considering explicit decimal rounding.
  • Reimplementing helpers such as hypot(), gcd(), or fsum() unnecessarily.

Practice

1. Calculate the area and circumference of a circle. 2. Find the distance between two two-dimensional points. 3. Calculate how many boxes are needed for 101 items when each box holds 12. 4. Compare 0.1 + 0.2 with 0.3 using isclose(). 5. Calculate the number of ways to choose three students from a group of ten.

Try the related tasks in the [interactive Python coding exercises](/codingexercises).