Math Library in Python
Math Library in Python
The math library in Python provides a wide range of mathematical functions to perform complex calculations easily. It includes constants, trigonometric functions, logarithmic operations, and more.
1. Importing the Math Library
To use the math library, you must import it using:
import math
---
2. Commonly Used Functions
Here are some commonly used functions in the math library:
A. Basic Mathematical Functions
math.sqrt(x)
Returns the square root of x.
Example:
print(math.sqrt(16)) # Output: 4.0
math.pow(x, y)
Returns x raised to the power of y.
Example:
print(math.pow(2, 3)) # Output: 8.0
math.ceil(x)
Rounds x up to the nearest integer.
Example:
print(math.ceil(4.3)) # Output: 5
math.floor(x)
Rounds x down to the nearest integer.
Example:
print(math.floor(4.7)) # Output: 4
B. Trigonometric Functions
math.sin(x), math.cos(x), math.tan(x)
Calculates the sine, cosine, and tangent of x (in radians).
Example:
print(math.sin(math.pi / 2)) # Output: 1.0
math.degrees(x)
Converts radians to degrees.
Example:
print(math.degrees(math.pi)) # Output: 180.0
math.radians(x)
Converts degrees to radians.
Example:
print(math.radians(180)) # Output: 3.141592653589793
C. Logarithmic and Exponential Functions
math.log(x)
Returns the natural logarithm of x (base e).
Example:
print(math.log(10)) # Output: 2.302585092994046
math.log10(x)
Returns the base-10 logarithm of x.
Example:
print(math.log10(100)) # Output: 2.0
math.exp(x)
Returns e raised to the power of x.
Example:
print(math.exp(2)) # Output: 7.38905609893065
D. Constants
math.pi
Value of π (Pi).
Example:
print(math.pi) # Output: 3.141592653589793
math.e
Value of Euler's number (e).
Example:
print(math.e) # Output: 2.718281828459045
---
3. Applications of Math Library
Used in scientific computations.
Supports geometry, trigonometry, and calculus.
Helpful for solving engineering problems.
---
4. Practice Example
import math
# Calculate area of a circle with radius 5
radius = 5
area = math.pi * math.pow(radius, 2)
print(f"Area of the circle: {area}")
# Convert 90 degrees to radians and find its sine
angle_degrees = 90
angle_radians = math.radians(angle_degrees)
sine_value = math.sin(angle_radians)
print(f"Sine of 90 degrees: {sine_value}")
Comments
Post a Comment