Python Math Module
The math module provides access to the mathematical functions defined by the C standard. These functions cannot be used with complex numbers; use the cmath module for complex support.
Importing the Module
import math
Constants
print(math.pi) # 3.141592...
print(math.e) # 2.718281...
print(math.inf) # Infinity
print(math.nan) # Not a Number
Numeric Functions
Rounding
x = 4.7
print(math.ceil(x)) # 5 (Round up)
print(math.floor(x)) # 4 (Round down)
print(math.trunc(x)) # 4 (Truncate decimal)
Absolute and Factorial
print(math.fabs(-5.5)) # 5.5 (Absolute value as float)
print(math.factorial(5)) # 120 (5 * 4 * 3 * 2 * 1)
Power and Logarithmic Functions
# Power and Root
print(math.pow(2, 3)) # 8.0 (2 to the power of 3)
print(math.sqrt(16)) # 4.0 (Square root)
# Logarithms
print(math.log(10)) # Natural log (base e)
print(math.log(100, 10)) # Log base 10 (Output: 2.0)
print(math.log10(100)) # Log base 10 convenience function
Trigonometry
Trigonometric functions expect angles in radians.
angle = math.radians(90) # Convert degrees to radians
print(math.sin(angle))
print(math.cos(angle))
print(math.tan(angle))
print(math.degrees(math.pi)) # Convert radians to degrees (180.0)