Sub topic 2
The math module: constants and everyday functions
This chapter assumes you can write Python functions and call them, and that you know what float and int are. You have already seen import. Here you will use it for the math module.
What `math` provides
math is a standard library module of numeric constants and functions. It works on real numbers (int and float). You import it once, then call everything through the math. prefix.
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793math.sqrt always returns a float, even when the answer is a whole number.
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` | `2 * pi`, one full turn in radians | 6.283185307179586 |
| `math.inf` | Positive infinity | `inf` |
| `math.nan` | "Not a number" | `nan` |
These are constants, not functions, so you write math.pi with no parentheses.
Powers, roots, and logarithms
math.sqrt(x)returns the square root.math.exp(x)returnseraised tox.math.log(x)returns the natural logarithm. A second argument sets the base.math.log2(x)andmath.log10(x)return base-2 and base-10 logarithms. They are more accurate thanmath.log(x, 2)ormath.log(x, 10).
import math
print(math.log2(8)) # 3.0
print(math.log10(1000)) # 3.0
print(math.exp(0)) # 1.0
print(math.log(math.e)) # 1.0
# How many years for money to double at 7% growth per year?
years = math.log(2) / math.log(1.07)
print(f"{years:.2f}") # 10.24Use the ** operator for ordinary powers such as 2 ** 10. It keeps integers as integers. math.pow(2, 10) always returns a float (1024.0).
Trigonometry and angles
math.sin, math.cos, and math.tan take angles in radians, not degrees. Convert with math.radians and math.degrees.
import math
print(math.degrees(math.pi)) # 180.0
print(math.radians(180)) # 3.141592653589793
print(math.cos(math.pi)) # -1.0
print(math.sin(math.pi)) # 1.2246467991473532e-16math.sin(math.pi) is not exactly 0 because math.pi is only an approximation of π. A later chapter covers how to compare such results safely.
Distances
math.dist(p, q) returns the straight-line distance between two points given as sequences of coordinates. math.hypot does the same for the length of a single vector.
import math
radius = 2
print(f"{math.pi * radius ** 2:.2f}") # 12.57
print(math.dist((0, 0), (3, 4))) # 5.0Errors, infinity, and NaN
A function called outside its domain raises ValueError. Results too large for a float raise OverflowError.
import math
try:
math.sqrt(-1)
except ValueError as exc:
print(exc) # math domain error
print(math.inf > 10 ** 100) # True
print(math.nan == math.nan) # False
print(math.isnan(math.nan)) # Truenan is never equal to anything, including itself. Test for it with math.isnan. Test for infinity with math.isinf.
Exercise
What does math.sqrt(-4) do, and how can you avoid the problem?
Show answer
It raises ValueError: math domain error because math works only with real numbers. Check that the value is at least 0 before calling it, or catch the ValueError. If you need a complex result, use cmath.sqrt(-4), which returns 2j.