The math module gathers the mathematical functions that are not included by default in the language: roots, rounding, trigonometry, logarithms and more. It always starts with import math.
Constants
import math
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
Roots and powers
print(math.sqrt(49)) # 7.0
print(math.pow(2, 10)) # 1024.0
print(2 ** 10) # 1024 (the ** operator returns an integer when it can)
print(math.hypot(3, 4)) # 5.0 (root of 3² + 4²)
math.sqrt fails with negative numbers:
math.sqrt(-1)
# ValueError: math domain error
Rounding
| Function | What it does | With 3.7 | With -3.7 |
|---|---|---|---|
math.floor(x) | integer downwards | 3 | -4 |
math.ceil(x) | integer upwards | 4 | -3 |
math.trunc(x) | removes the decimal part | 3 | -3 |
round(x) | nearest integer (Python function) | 4 | -4 |
print(math.floor(3.7), math.ceil(3.7), math.trunc(3.7)) # 3 4 3
print(math.floor(-3.7), math.ceil(-3.7), math.trunc(-3.7)) # -4 -3 -3
Integers: GCD, factorial and combinatorics
print(math.gcd(12, 18)) # 6 greatest common divisor
print(math.factorial(5)) # 120 (5 · 4 · 3 · 2 · 1)
print(math.comb(5, 2)) # 10 combinations: choose 2 of 5 regardless of order
print(math.perm(5, 2)) # 20 permutations: choose 2 of 5 where order matters
The least common multiple is calculated with the formula a * b // math.gcd(a, b).
Logarithms
print(math.log(math.e)) # 1.0 natural logarithm
print(math.log10(1000)) # 3.0
print(math.log2(8)) # 3.0
Trigonometry: in radians!
The sin, cos and tan functions work with radians, not degrees. To convert use math.radians and math.degrees:
angle = math.radians(90)
print(round(math.sin(angle), 2)) # 1.0
print(math.degrees(math.pi)) # 180.0
Comparing decimals with isclose
Decimals are stored with tiny errors, so comparing with == can fail:
print(0.1 + 0.2 == 0.3) # False
print(math.isclose(0.1 + 0.2, 0.3)) # True
Practice in Hypotenuse, Circle area and circumference, Floor, ceiling and truncation, Greatest common divisor and least common multiple and Combinations and permutations.