Python - Math
Overview
Estimated time: 10–20 minutes
Use the math module for common mathematical functions and constants.
Learning Objectives
- Use mathfunctions likesqrt,ceil,floor, and trigonometry.
- Access constants like piande.
- Know when to prefer decimalfor 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 mathfunctions work on complex numbers; usecmathfor complex.
- Expecting exact decimal arithmetic; use decimalwhen 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.