Python Numbers and Math · Lesson 17 of 149

Python math Module

What you will learn

  • How to import the math module
  • The constants math.pi, math.e, math.inf and math.nan
  • Roots, powers, floor, ceil and trunc
  • Logarithms and trigonometry (angles in radians)
  • Factorials, combinations, gcd and lcm
  • Distance, isclose and testing for inf and nan

1. Importing math

Python's built-in functions (lesson 3.3) cover everyday needs. For more maths, import the math module. A module is a file of ready-made tools. You import it once at the top of your program, then use its tools with a dot:

import math

print(math.sqrt(16))
4.0

math.sqrt means "the sqrt tool inside math". Chapter 16 explains modules fully. To see everything in the module, type help(math) in the shell (lesson 1.4).

Quick check: what do you write to use the square root function?

import math once, then math.sqrt(...).

2. Constants

Name Value Meaning
math.pi 3.141592653589793 π, the ratio of a circle's circumference to its diameter
math.e 2.718281828459045 Euler's number, the base of natural logarithms
math.tau 6.283185307179586 2π, one full turn
math.inf inf infinity
math.nan nan "not a number"
import math

print(math.pi * 5 ** 2)
print(round(math.pi * 5 ** 2, 2))
print(2 * math.pi * 5)
78.53981633974483
78.54
31.41592653589793

That is the area and circumference of a circle with radius 5.

3. Roots and powers

import math

print(math.sqrt(16), math.sqrt(2))
print(math.isqrt(17), math.isqrt(16))
print(math.pow(2, 3), 2 ** 3)
4.0 1.4142135623730951
4 4
8.0 8
  • math.sqrt(x) is the square root, always a float.
  • math.isqrt(n) is the whole-number square root (rounded down) of a whole number, exact even for huge values.
  • math.pow(2, 3) always returns a float; the ** operator keeps int results, so it is usually better.

The square root of a negative number is an error here:

math.sqrt(-1)
ValueError: math domain error

("Domain error" means the input is outside what the function accepts.) Lesson 3.8 shows how complex numbers handle this.

4. Floor, ceil and trunc

Three ways to turn a decimal into a whole number:

Function Rule 3.7 -3.7
math.floor(x) round down (towards minus infinity) 3 -4
math.ceil(x) round up (towards plus infinity) 4 -3
math.trunc(x) cut the decimals (towards zero) 3 -3
round(x) round to the nearest (ties to even) 4 -4
import math

print(math.floor(3.7), math.floor(-3.2), math.ceil(3.2), math.ceil(-3.7))
print(math.trunc(3.7), math.trunc(-3.7), int(-3.7), round(-3.7))
3 -4 4 -3
3 -3 -3 -4

math.trunc(x) does the same as int(x). All three give an int.

A handy use of ceil: how many boxes of 4 do I need for 7 items?

import math
print(math.ceil(7 / 4))
2

5. Factorials, combinations, gcd and lcm

import math

print(math.factorial(5), math.factorial(20))
print(math.comb(5, 2), math.perm(5, 2))
print(math.gcd(12, 18), math.lcm(4, 6))
120 2432902008176640000
10 20
6 12
Function Meaning
math.factorial(n) n × (n-1) × ... × 1, so 5! is 120
math.comb(n, k) ways to choose k items from n, order ignored
math.perm(n, k) ways to arrange k items out of n, order counts
math.gcd(a, b) the greatest common divisor
math.lcm(a, b) the least common multiple

math.comb(5, 2) is 10: there are 10 ways to pick 2 people from 5. math.perm(5, 2) is 20: there are 20 ways to give two different prizes to 2 of 5 people. A negative number is an error: math.factorial(-1) raises ValueError: factorial() not defined for negative values.

6. Logarithms and powers of e

import math

print(math.exp(1), math.log(math.e))
print(math.log10(1000), math.log2(8), math.log(8, 2))
2.718281828459045 1.0
3.0 3.0 3.0
  • math.exp(x) is e to the power x.
  • math.log(x) is the natural logarithm (base e); math.log(x, base) uses another base.
  • math.log10(x) and math.log2(x) are shortcuts for base 10 and base 2.

math.log(0) is an error (ValueError: math domain error), because no power gives zero. A power of e that is too large is also an error: math.exp(710) raises OverflowError: math range error.

7. Trigonometry: radians, not degrees

sin, cos, tan and their inverses (asin, acos, atan, atan2) use radians. A full turn is 2π radians, or 360 degrees. Convert with math.radians and math.degrees:

import math

print(math.degrees(math.pi), math.radians(180))
print(math.sin(math.pi / 2), math.cos(0))
print(math.sin(math.radians(30)))
180.0 3.141592653589793
1.0 1.0
0.49999999999999994

Notice sin(30°) is 0.49999999999999994, not exactly 0.5: these are floats (lesson 3.4). Likewise math.sin(math.pi) is 1.2246467991473532e-16, not 0. Use math.isclose(..., abs_tol=1e-9) to test such results.

8. Distance, hypot and the rest

import math

print(math.hypot(3, 4), math.dist((0, 0), (3, 4)))
print(math.fabs(-2), math.prod([1, 2, 3, 4]))
print(math.isfinite(1.0), math.isfinite(math.inf), math.isinf(math.inf), math.isnan(math.nan))
5.0 5.0
2.0 24
True False True True
  • math.hypot(3, 4) is the length of the long side of a right triangle with sides 3 and 4.
  • math.dist(p, q) is the straight-line distance between two points.
  • math.prod(...) multiplies the values of a collection, like sum adds them.
  • math.isclose, math.fsum, math.isfinite, math.isinf and math.isnan complete the toolbox from lesson 3.4.

math.fmod(-7, 2) is -1.0, while -7 % 2 is 1 (lesson 3.2): fmod keeps the sign of the first number, % the sign of the second.

Worked example: the distance between two cities on a map

City A is at map position (2, 3) and city B at (8, 11), in kilometres. How far apart are they in a straight line?

import math

a = (2, 3)
b = (8, 11)
print(math.dist(a, b))
10.0
Step Calculation Result
1 across: 8 - 2 6
2 up: 11 - 3 8
3 sqrt(6² + 8²) = sqrt(100) 10.0

The two sides, 6 and 8, make a right triangle whose long side is 10. The positions are made-up numbers.

Common mistakes

  • Forgetting import math, which gives NameError: name 'math' is not defined.
  • Writing sqrt(16) instead of math.sqrt(16).
  • Passing degrees to sin or cos. Convert with math.radians.
  • Confusing floor, ceil, trunc and round for negative numbers.
  • Expecting math.sin(math.pi) to be exactly 0. Use isclose with abs_tol.
  • Naming your own file math.py. It hides the real module and breaks imports.

Key takeaways

  • import math once, then call math.sqrt, math.floor and the rest.
  • Constants: math.pi, math.e, math.tau, math.inf, math.nan.
  • floor rounds down, ceil up, trunc cuts towards zero, round goes to the nearest.
  • Trigonometric functions use radians; convert with radians and degrees.
  • factorial, comb, perm, gcd, lcm, hypot, dist and prod solve many common tasks in one call.

Practice

1. Write two lines that print the area of a circle of radius 3, rounded to 2 decimals.

Show answer

import math, then print(round(math.pi * 3 ** 2, 2)), which gives 28.27.

2. What do math.floor(-2.5), math.ceil(-2.5) and math.trunc(-2.5) give?

Show answer

-3, -2 and -2.

3. You need to pack 25 items into boxes of 6. How many boxes?

Show answer

math.ceil(25 / 6) gives 5 boxes (four full boxes hold 24, and one more is needed for the last item).

4. How many ways are there to choose 3 players from 10? Which function?

Show answer

math.comb(10, 3) gives 120.

5. Find sin of 90 degrees using the math module.

Show answer

math.sin(math.radians(90)), which gives 1.0.

6. What is the greatest common divisor and the least common multiple of 8 and 12?

Show answer

math.gcd(8, 12) is 4 and math.lcm(8, 12) is 24.