Python Math

Python Math Module Tutorial

Python provides a built-in math module for performing mathematical operations like trigonometry, logarithms, factorials, and more.


1. Importing the Math Module

To use the math module, you must import it first:

import math

2. Basic Math Functions

2.1 Rounding Numbers

print(math.ceil(4.3))   # Output: 5 (Round up)
print(math.floor(4.9))  # Output: 4 (Round down)

ceil() rounds up, floor() rounds down.

2.2 Factorial and Power

print(math.factorial(5))  # Output: 120 (5! = 5 × 4 × 3 × 2 × 1)
print(math.pow(2, 3))     # Output: 8.0 (2³)
print(math.sqrt(25))      # Output: 5.0 (Square root)

Use factorial(), pow(), and sqrt() for calculations.


3. Logarithmic Functions

3.1 Natural Logarithm (Base e)

print(math.log(10))  # Output: 2.302 (ln(10))

3.2 Logarithm with Base 10

print(math.log10(100))  # Output: 2.0 (log₁₀(100))

Use log() for natural log and log10() for base 10.


4. Trigonometric Functions

4.1 Converting Degrees to Radians

print(math.radians(180))  # Output: 3.14159 (π radians)

4.2 Sin, Cos, and Tan

print(math.sin(math.radians(30)))  # Output: 0.5
print(math.cos(math.radians(60)))  # Output: 0.5
print(math.tan(math.radians(45)))  # Output: 1.0

✅ **sin(), cos(), and tan() require angles in radians.


5. Constants in Math Module

print(math.pi)   # Output: 3.141592653589793
print(math.e)    # Output: 2.718281828459045

Use math.pi for π and math.e for Euler’s number.


6. Greatest Common Divisor (GCD) & Least Common Multiple (LCM)

print(math.gcd(24, 36))  # Output: 12 (Greatest Common Divisor)
print(math.lcm(4, 6))    # Output: 12 (Least Common Multiple)

Use gcd() for Greatest Common Divisor and lcm() for Least Common Multiple.


Conclusion

The math module is powerful for performing advanced calculations and is widely used in scientific computing, engineering, and data analysis.

Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment