Python ยท Chapter 35 of 45
Math Module
The `math` module provides constants and functions for numeric math: `pi`, `e`, `sqrt`, `sin`, `cos`, `log`, `factorial`, `ceil`, `floor`.
For whole-number-only functions use `math.floor`/`math.ceil`; for random numbers use the `random` module.
Common functions
`sqrt(x)`, `pow(x,y)`, `log(x)`, `sin(x)`, `factorial(n)`, `gcd(a,b)`.
Constants
`math.pi`, `math.e`, `math.inf`, `math.nan`.
Example 1 (python)
import math
print(math.sqrt(50))
print(math.pi)
print(math.factorial(5))Output
7.0710678118654755
3.141592653589793
120Common math functions and constants.
Example 2 (python)
import math
print(math.ceil(4.1))
print(math.floor(4.9))Output
5
4Round up (ceil) and down (floor).
Key points
- `import math` first.
- Includes trig, log, sqrt, factorial.
- Constants: pi, e, inf, nan.
- For random values use `random`, not `math`.
๐ก Note: For heavy numeric work with arrays, use NumPy โ it is orders of magnitude faster than pure Python.
