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

ConstantMeaningExample
math.piValue of π (3.14159…)math.pi
math.eEuler’s number (2.71828…)math.e
math.infInfinitymath.inf
math.nanNot a numbermath.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

FunctionDescriptionExample
math.ceil(x)Round upmath.ceil(4.2) → 5
math.floor(x)Round downmath.floor(4.8) → 4
math.trunc(x)Removes decimalsmath.trunc(4.9) → 4

 4. Logarithmic Functions

FunctionDescription
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.

FunctionExample
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

CategoryFunctions
Constantspi, e, inf, nan
Trigonometrysin(), cos(), tan(), radians(), degrees()
Logarithmslog(), log10(), log2()
Roundingceil(), floor(), trunc()
Power & Rootssqrt(), pow()
Combinatoricsfactorial(), comb(), perm()
Otherfabs(), gcd(), isfinite()

You may also like...