The math module is part of Python’s standard library. It provides functions for common mathematical operations including rounding, trigonometric calculations, logarithms, and constants like pi and e.
Syntax
import math
Key Functions
Numerical Operations
Function
Signature
Description
ceil()
ceil(x)
Returns the smallest integer greater than or equal to x
floor()
floor(x)
Returns the largest integer less than or equal to x
sqrt()
sqrt(x)
Returns the square root of x
pow()
pow(x, y)
Returns x raised to the power of y
factorial()
factorial(n)
Returns n! (n factorial)
gcd()
gcd(a, b)
Returns the greatest common divisor of a and b
fabs()
fabs(x)
Returns the absolute value of x as a float
Trigonometric Functions
Function
Signature
Description
sin()
sin(x)
Returns the sine of x (x in radians)
cos()
cos(x)
Returns the cosine of x (x in radians)
tan()
tan(x)
Returns the tangent of x (x in radians)
degrees()
degrees(x)
Converts radians to degrees
radians()
radians(x)
Converts degrees to radians
Logarithmic and Exponential
Function
Signature
Description
log()
log(x[, base])
Returns the natural logarithm of x, or to the given base
import mathvalues = [0.1] * 10total = sum(values) # May not be exactly 1.0print(total) # 0.9999999999999999# Use math.fsum for floating-point precisionprint(math.fsum(values)) # 1.0
Finding the hypotenuse
import math# Pythagorean theorem: c = sqrt(a² + b²)a, b = 3, 4c = math.hypot(a, b)print(c) # 5.0