Python Math
Python offers built-in math functions plus a math module that unlocks more advanced mathematical operations.
Built-in math functions
Some mathematical work needs no imports at all. Python always makes a handful of numeric functions available, including min() and max() to find the smallest or largest value, abs() for the absolute value, and pow() or the ** operator to raise a number to a power.
Using the always-available functions
print(min(5, 12, 3)) # 3
print(max(5, 12, 3)) # 12
print(abs(-7.4)) # 7.4
print(pow(2, 5)) # 32 (same as 2 ** 5)
print(round(3.14159, 2)) # 3.14The math module
For anything beyond the basics, import the math module. It provides functions for square roots, rounding in a specific direction, trigonometry, factorials, and useful constants such as pi and the mathematical constant e.
Common math module functions
import math
print(math.sqrt(64)) # 8.0
print(math.ceil(4.1)) # 5 (rounds up)
print(math.floor(4.9)) # 4 (rounds down)
print(math.factorial(5))# 120
print(math.pi) # 3.141592653589793- math.ceil(x) rounds a number up to the nearest whole number.
- math.floor(x) rounds a number down to the nearest whole number.
- math.sqrt(x) returns the square root as a float.
- math.pow(x, y) returns x raised to the power y as a float.
- math.gcd(a, b) returns the greatest common divisor of two integers.
Trigonometry and logarithms
import math
# Trig functions expect radians
angle = math.radians(90)
print(round(math.sin(angle), 2)) # 1.0
print(math.log(math.e)) # 1.0 (natural log)
print(math.log10(1000)) # 3.0Exercise: Python Math
What happens when you call `math.sqrt(x)` with a negative value of x?