Python Math
Python · Working with Data
Theory
The built-in math module adds mathematical functions beyond the basic + - * / operators. Common ones are sqrt() for square root, pow() for powers, ceil() to round up to the next whole number, floor() to round down, trunc() to drop the decimal part, log() and exp() for logarithms and exponentials, and sin()/cos() for trigonometry. It also provides the constants math.pi and math.e.
math.sqrt(16) returns 4.0 (always a float), math.ceil(4.2) returns 5 and math.floor(4.2) returns 4. With negatives the difference matters: ceil(-4.2) is -4 and floor(-4.2) is -5, while trunc(-4.2) is -4. math works on single numbers; for whole arrays of numbers, NumPy's versions (np.sqrt) are much faster.
Why we use it
Analytics and finance code constantly needs rounding rules, square roots, logs and growth calculations. math gives tested, precise implementations so you do not have to write them yourself.
When to use it
Use math for scalar calculations in plain Python. For lists or columns of numbers use NumPy or pandas, and for money that must not suffer float rounding, use the decimal module.
How it works
- import math
- Pick the function: sqrt, ceil, floor, log ...
- Pass a number
- Is the input valid for the function? Yes: Return the result. No: Raise ValueError (e.g. sqrt(-1)).
- Use the result in your calculation
Syntax
import math
math.sqrt(x)Example
math.sqrt(16) # 4.0
math.ceil(4.2) # 5Key points
- Includes trig, logarithmic, and rounding functions
- math.pi and math.e are useful constants
- math.sqrt() always returns a float
- ceil and floor differ from trunc for negative numbers
- Invalid input like math.sqrt(-1) raises ValueError