← Back to Python Course | Chapter 12: Standard Library | Lesson 3 of 9

Python math Module

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

python
import math
print(math.floor(4.7))
print(math.ceil(4.2))
print(round(4.5))

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

python
import math
print(math.sqrt(16))
print(math.pow(2, 3))

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

python
import math
angle = math.radians(90)
print(math.sin(angle))

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

python
import math
print(math.log(math.e))
print(math.log10(1000))
print(math.log2(8))

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

python
import math
print(math.pi)
print(math.tau)
print(math.e)

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.