🧮 Python Math Module
Python includes a built-in module called math that provides mathematical functions like square root, logarithms, trigonometry, constants, rounding, etc.
To use the math module, you must first import it:
1. Math Constants
| Constant |
Meaning |
Example |
math.pi |
Value of π (3.14159…) |
math.pi |
math.e |
Euler’s number (2.71828…) |
math.e |
math.inf |
Infinity |
math.inf |
math.nan |
Not a number |
math.nan |
Example:
2. Basic Math Functions
math.sqrt() — Square Root
math.pow() — Power (similar to **)
math.pow() always returns float; ** keeps type.
3. Rounding Functions
| Function |
Description |
Example |
math.ceil(x) |
Round up |
math.ceil(4.2) → 5 |
math.floor(x) |
Round down |
math.floor(4.8) → 4 |
math.trunc(x) |
Removes decimals |
math.trunc(4.9) → 4 |
4. Logarithmic Functions
| Function |
Description |
math.log(x) |
Natural log (base e) |
math.log10(x) |
Base-10 log |
math.log2(x) |
Base-2 log |
Example:
5. Trigonometric Functions
All angles must be in radians.
| Function |
Example |
math.sin(x) |
math.sin(math.pi/2) → 1 |
math.cos(x) |
math.cos(0) → 1 |
math.tan(x) |
math.tan(math.pi/4) → 1 |
Convert Degrees ↔ Radians
6. Factorial & Combinations
Factorial
Combination (N Choose R)
Permutation
7. Absolute and GCD
Absolute Value
Greatest Common Divisor
8. Using math.isfinite, isnan, isinf
Example Program Using Math Module
🎯 Summary
| Category |
Functions |
| Constants |
pi, e, inf, nan |
| Trigonometry |
sin(), cos(), tan(), radians(), degrees() |
| Logarithms |
log(), log10(), log2() |
| Rounding |
ceil(), floor(), trunc() |
| Power & Roots |
sqrt(), pow() |
| Combinatorics |
factorial(), comb(), perm() |
| Other |
fabs(), gcd(), isfinite() |