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:

import math

print(math.pi)
print(math.e)
print(math.inf)


๐Ÿ“Œ 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:

print(math.log(10))
print(math.log10(10))
print(math.log2(8))

๐Ÿ“Œ 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

print(math.isinf(math.inf)) # True
print(math.isnan(math.nan)) # True
print(math.isfinite(10)) # True

๐Ÿ“Œ Example Program Using Math Module

import math

radius = 4

area = math.pi * radius**2
circumference = 2 * math.pi * radius

print(“Area:”, area)
print(“Circumference:”, circumference)


๐ŸŽฏ 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()

CodeCapsule

Sanjit Sinha โ€” Web Developer | PHP โ€ข Laravel โ€ข CodeIgniter โ€ข MySQL โ€ข Bootstrap Founder, CodeCapsule โ€” Student projects & practical coding guides. Email: info@codecapsule.in โ€ข Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *