Python Math Module

🧮 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:

import math

 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

print(math.sqrt(25)) # 5.0

math.pow() — Power (similar to **)

print(math.pow(2, 3)) # 8.0

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

print(math.radians(180)) # 3.14159...
print(math.degrees(math.pi)) # 180

 6. Factorial & Combinations

 Factorial

print(math.factorial(5)) # 120

 Combination (N Choose R)

print(math.comb(5, 2)) # 10

 Permutation

print(math.perm(5, 2)) # 20

 7. Absolute and GCD

 Absolute Value

print(math.fabs(-5.5)) # 5.5

 Greatest Common Divisor

print(math.gcd(24, 36)) # 12

 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()

You may also like...