Ticker

6/recent/ticker-posts

Math Module in Python

Math Module in Python

Introduction 

The Math module in Python is a built-in module that provides a set of mathematical functions and constants. It allows you to perform various mathematical operations without having to write custom functions for them.

Math Module Functions and Constants

  1. Math Functions

    • math.ceil(x): Returns the smallest integer greater than or equal to x.
    • math.floor(x): Returns the largest integer less than or equal to x.
    • math.trunc(x): Returns the truncated integer value of x.
    • math.sqrt(x): Returns the square root of x.
    • math.pow(x, y): Returns x raised to the power y.
    • math.exp(x): Returns the exponential value of x (e^x).
    • math.log(x, base): Returns the natural logarithm of x with a given base (default is e).
    • math.log10(x): Returns the base-10 logarithm of x.
    • math.sin(x): Returns the sine of x in radians.
    • math.cos(x): Returns the cosine of x in radians.
    • math.tan(x): Returns the tangent of x in radians.
    • math.radians(x): Converts angle x from degrees to radians.
    • math.degrees(x): Converts angle x from radians to degrees.
  2. Math Constants

    • math.pi: Represents the constant Ï€ (pi) with a value of approximately 3.141592653589793.
    • math.e: Represents the constant e with a value of approximately 2.718281828459045.

Coding Example and Explanation

python
import math

# Example 1: Using math.ceil() and math.floor()
num = 4.75
ceil_result = math.ceil(num)
floor_result = math.floor(num)
print("Ceil Result:", ceil_result) # Output: 5
print("Floor Result:", floor_result) # Output: 4

# Example 2: Using math.sqrt() and math.pow()
x = 16
square_root = math.sqrt(x)
power_result = math.pow(x, 3)
print("Square Root:", square_root) # Output: 4.0
print("Power Result:", power_result) # Output: 4096.0

# Example 3: Using math.sin() and math.radians()
angle_degrees = 30
angle_radians = math.radians(angle_degrees)
sin_result = math.sin(angle_radians)
print("Sin Result:", sin_result) # Output: 0.49999999999999994

In this documentation, we covered an overview of the Math module, its functions, and constants. We also provided coding examples demonstrating how to use some of the functions with explanations of their results. Remember to import the Math module before using its functions in your Python code.

Post a Comment

0 Comments