๐งฎ 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() |