Sub topic 2
The math module: constants and everyday functions
This chapter assumes you know basic Python syntax, including functions and import, and that you can run a script or use the interactive interpreter. It also assumes you know the difference between int and float. The math module is part of the standard library, so there is nothing to install.
What the module is for
math wraps the C library's floating-point functions. Almost every function takes a real number and returns a float. Python has built-in numeric tools (abs, pow, min, max, sum, round, **), and math adds what they lack: roots, logarithms, trigonometry, and constants such as pi.
Import the module and call functions with the math. prefix:
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793You can also import names directly with from math import sqrt, pi. Keeping the prefix makes the origin of each name obvious and avoids clashes with your own variables, such as a variable called e or pi.
The module only works with real numbers. For complex numbers, use cmath, which has the same function names.
Constants
| Name | Meaning | Value |
|---|---|---|
| `math.pi` | Ratio of a circle's circumference to its diameter | 3.141592653589793 |
| `math.e` | Base of natural logarithms | 2.718281828459045 |
| `math.tau` | Full circle in radians, 2π | 6.283185307179586 |
| `math.inf` | Positive infinity | `inf` |
| `math.nan` | "Not a number" | `nan` |
These are ordinary floats, so they are approximations. math.tau is useful because a full turn is tau radians, a half turn is tau / 2, and a quarter turn is tau / 4.
import math
radius = 2.5
print(math.pi * radius ** 2) # area of a circle
print(math.tau * radius) # circumferenceRoots, powers, and absolute values
math.sqrt(x) returns the square root as a float, even for perfect squares. It rejects negative numbers.
import math
print(math.sqrt(16)) # 4.0
print(math.pow(2, 0.5)) # 1.4142135623730951
print(2 ** 0.5) # 1.4142135623730951
print(math.fabs(-3)) # 3.0
print(abs(-3)) # 3
print(math.cbrt(27)) # 3.0 (Python 3.11 and later)math.pow and ** differ in two ways:
math.powalways converts its arguments to floats and returns a float.2 ** 3returns the integer8, andmath.pow(2, 3)returns8.0.**works on arbitrarily large integers without losing precision.math.powis limited to float range and raisesOverflowErrorwhen the result is too large.
Use ** for integer powers and math.pow only when you want C-style float behavior. math.fabs always returns a float, while the built-in abs keeps the input type. Prefer abs in most code.
math.prod multiplies the items of an iterable, as sum adds them:
import math
print(math.prod([1, 2, 3, 4])) # 24
print(math.prod([])) # 1Exponentials and logarithms
math.exp(x) computes e raised to x. math.log(x) is the natural logarithm, the inverse of exp. Two specialized functions, log2 and log10, are more exact than dividing logarithms yourself.
import math
print(math.exp(0)) # 1.0
print(math.log(math.e)) # 1.0
print(math.log2(8)) # 3.0
print(math.log10(1000)) # 3.0
print(math.log(100, 10)) # 2.0The two-argument form math.log(x, base) divides two logarithms internally. Prefer log2 or log10 when the base is 2 or 10.
A practical use is compound growth. With a 7 percent yearly return, solve (1.07) ** years == 2 for the doubling time:
import math
rate = 0.07
years = math.log(2) / math.log(1 + rate)
print(round(years, 2)) # 10.24For very small x, 1 + x loses precision. math.log1p(x) computes log(1 + x) accurately, and math.expm1(x) computes exp(x) - 1 accurately. You need these only when values are near zero, such as tiny interest rates.
Trigonometry and angles
All trigonometric functions use radians, not degrees. This is the most common source of wrong answers. Convert with math.radians and math.degrees.
import math
print(math.sin(math.pi / 2)) # 1.0
print(math.cos(math.pi)) # -1.0
print(math.radians(180)) # 3.141592653589793
print(math.degrees(math.pi)) # 180.0
print(math.sin(math.pi)) # 1.2246467991473532e-16The last line shows why: pi is only an approximation, so sin(pi) is a tiny number close to zero instead of exactly 0.0. Compare such results with a tolerance, as the later chapter on floating-point precision explains.
The inverse functions are asin, acos, and atan. They return radians. asin and acos accept only values from -1 to 1.
For converting coordinates, use math.atan2(y, x) instead of math.atan(y / x). It takes both coordinates, so it knows the quadrant and does not fail when x is 0.
import math
x, y = 1, 1
radius = math.hypot(x, y)
angle = math.degrees(math.atan2(y, x))
print(radius) # 1.4142135623730951
print(angle) # 45.0math.hypot returns the length of the vector. It accepts any number of arguments, and it is safer than sqrt(x*x + y*y) because it avoids intermediate overflow. For the distance between two points, math.dist takes two coordinate sequences:
import math
print(math.hypot(3, 4)) # 5.0
print(math.dist((0, 0), (3, 4))) # 5.0Infinity and NaN
Floats can represent infinity and "not a number". math.inf compares greater than any finite number, which makes it a convenient starting value when searching for a minimum:
import math
smallest = math.inf
for value in [8.5, 3.2, 9.9]:
if value < smallest:
smallest = value
print(smallest) # 3.2NaN is special because it is not equal to anything, including itself. Test for it with math.isnan, never with ==:
import math
value = math.nan
print(value == math.nan) # False
print(math.isnan(value)) # True
print(math.isinf(-math.inf)) # True
print(math.isfinite(1.5)) # TrueErrors you will meet
When an input is outside a function's domain, math raises an exception instead of returning NaN. A mathematically impossible input raises ValueError. A result too large for a float raises OverflowError.
import math
for call in (lambda: math.sqrt(-1),
lambda: math.log(0),
lambda: math.exp(1000)):
try:
call()
except (ValueError, OverflowError) as exc:
print(type(exc).__name__, "-", exc)This prints:
ValueError - math domain error
ValueError - math domain error
OverflowError - math range errorCheck the input before the call when bad data is expected, or catch the specific exception where you can recover. Note that math.log(0) is a domain error because the logarithm of zero is undefined.
Remainders: fmod versus %
math.fmod(a, b) and the % operator both give a remainder, but they treat negative numbers differently. The % result takes the sign of the divisor, and fmod takes the sign of the dividend, as in C.
import math
print(-7 % 3) # 2
print(math.fmod(-7, 3)) # -1.0For most Python code, % is what you want. Use fmod when you need C-compatible results or work with floats.
Choosing a function
Rounding, safe float comparison, and integer helpers such as factorial and gcd are covered in the next chapters. They also live in math.
Common mistakes
- Passing degrees to
sinorcos. Always convert withmath.radiansfirst. - Testing for NaN with
==. Usemath.isnan. - Expecting
math.sqrt(-1)to return a complex number. It raisesValueError. Usecmath.sqrtfor that. - Using
math.powfor large integer powers. Use**, which keeps exact integers. - Writing
math.sqrt(x*x + y*y)whenmath.hypot(x, y)is safer and clearer. - Naming your own script
math.py. Python would import your file instead of the standard module, andimport mathwould fail with confusing errors.
Exercise
A ladder 5 m long leans against a wall with its foot 3 m from the wall. Using the math module, compute (a) the height the ladder reaches on the wall and (b) the angle between the ladder and the ground in degrees, rounded to 1 decimal place.
Show answer
The height is the other leg of a right triangle, so use the Pythagorean relation. The angle comes from the inverse cosine of adjacent over hypotenuse. import math height = math.sqrt(5 2 - 3 2) # 4.0 angle = math.degrees(math.acos(3 / 5)) # about 53.13 print(height) print(round(angle, 1)) # 53.1
Exercise
What does each of these produce, and why? (a) math.sqrt(-9) (b) math.nan == math.nan (c) math.fmod(-7, 3) (d) 2 ** 3 versus math.pow(2, 3)
Show answer
(a) It raises ValueError ("math domain error") because the real square root of a negative number is undefined. (b) False, because NaN is not equal to anything, including itself. Use math.isnan to test for it. (c) -1.0, because fmod gives the remainder with the sign of the dividend, while -7 % 3 gives 2. (d) 2 ** 3 is the integer 8, and math.pow(2, 3) is the float 8.0, because math.pow always works with floats.