Python Math Module

The math module provides mathematical functions such as sqrt, ceil, floor, pi, and isclose.

import math

The functions in math work with regular numbers and return int or float values. For lists of numbers, see the statistics module.

Basic functions

import math

print(math.sqrt(81))
print(math.ceil(3.2))
print(math.floor(3.8))
9.0
4
3

Constants

The module also exposes useful mathematical constants.

import math

print(math.pi)
print(math.e)
3.141592653589793
2.718281828459045

Comparing floating-point numbers

isclose is safer than checking floats with ==.

import math

result = 0.1 + 0.2
print(result == 0.3)
print(math.isclose(result, 0.3))
False
True

Trigonometry

Angles are measured in radians. Use radians() when you have degrees.

import math

angle = math.radians(90)
print(math.sin(angle))
1.0

Greatest common divisor

gcd is useful when simplifying ratios.

import math

print(math.gcd(12, 18))
6