Python math Module
In this page:
import math
math.function_name(number) # e.g. math.sqrt(number)
math.pi
Rounding Numbers
The math module wraps the C standard library's math functions for fast numeric computation.
math.floor() always rounds a value down toward negative infinity and math.ceil() always rounds up toward positive infinity, which differs from Python's built-in round() that rounds to the nearest value using banker's rounding.
Example: Rounding Numbers
import math
print(math.floor(4.7)) # rounds down toward negative infinity
print(math.ceil(4.2)) # rounds up toward positive infinity
print(round(4.5)) # built-in round(), uses banker's rounding
Powers and Square Roots
math.sqrt() computes a square root and raises ValueError for negative inputs, since it only works with real numbers (use the separate cmath module if you need complex results).
math.pow() raises a number to a given power and always returns a float, unlike the ** operator, which preserves integer results when both operands are integers.
Example: Powers and Square Roots
import math
print(math.sqrt(16)) # square root
print(math.pow(2, 3)) # always returns a float, unlike **
Trigonometric Functions
math.sin(), math.cos(), and math.tan() all expect their input angle in radians, not degrees -- a very common source of subtly wrong output for beginners.
Use math.radians() to convert a degree value into radians before passing it to any trigonometric function.
Example: Trigonometric Functions
import math
angle = math.radians(90) # convert degrees to radians first
print(math.sin(angle)) # trig functions expect radians, not degrees
Logarithmic Functions
math.log() computes the natural logarithm (base e) by default, but accepts an optional second argument to compute a logarithm in any other base.
math.log10() and math.log2() are separate, more numerically precise shortcuts for the two bases used most often in practice.
Example: Logarithmic Functions
import math
print(math.log(math.e)) # natural log, base e
print(math.log10(1000)) # base 10
print(math.log2(8)) # base 2
Mathematical Constants
math.pi, math.tau (2π), and math.e are pre-computed to full floating-point precision, sparing you from hardcoding an approximation like 3.14159 that would introduce small but real errors into scientific or engineering calculations.
Example: Mathematical Constants
import math
print(math.pi) # precomputed to full floating-point precision
print(math.tau) # 2 * pi
print(math.e)
- Calling
sqrt(x)without themath.prefix or import, which raisesNameError. - Passing a negative number to
math.sqrt(-1), which raisesValueError. - Passing degrees to
math.sin(), which expects radians; convert withmath.radians().
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: