Python - Math
Overview
Estimated time: 10–20 minutes
Use the math
module for common mathematical functions and constants.
Learning Objectives
- Use
math
functions likesqrt
,ceil
,floor
, and trigonometry. - Access constants like
pi
ande
. - Know when to prefer
decimal
for precision.
Prerequisites
Examples
import math
print(math.sqrt(16))
print(math.ceil(3.14), math.floor(3.14))
print(math.sin(math.pi / 2))
Common Pitfalls
- Assuming
math
functions work on complex numbers; usecmath
for complex. - Expecting exact decimal arithmetic; use
decimal
when needed.
Checks for Understanding
- Which module handles complex-number math?
- How do you round up a number?
Show answers
cmath
math.ceil(x)
Exercises
- Given a list of floats, print their squares rounded up to the nearest int.
- Compute the hypotenuse given two sides using
math.hypot
.