Introduction to Python Math
Python Math
The math
module provides a set of mathematical functions and constants for performing various mathematical operations.
It allows you to perform calculations involving numbers, trigonometry, logarithms, exponentiation, and more.
Here's an overview of how to use the math
module in Python:
Importing the math Module
Before using the functions and constants from the math
module, you need to import it.
import math
Mathematical Functions
The math
module provides a wide range of mathematical functions.
Here are some commonly used functions:
math.sqrt(x):
Returns the square root ofx
.math.exp(x):
Returns the exponential ofx
(e^x).math.log(x):
Returns the natural logarithm (base e) ofx
.math.log10(x):
Returns the base-10 logarithm ofx
.math.sin(x), math.cos(x), math.tan(x):
Returns the sine, cosine, and tangent of x, respectively (wherex
is in radians).math.degrees(x):
Convertsx
from radians to degrees.math.radians(x):
Convertsx
from degrees to radians.math.ceil(x):
Returns the smallest integer greater than or equal tox
.math.floor(x):
Returns the largest integer less than or equal tox
.math.pow(x, y):
Returnsx
raised to the power ofy
.math.factorial(x):
Returns the factorial ofx
.
Mathematical Constants
The math
module also provides several mathematical constants. Some commonly used constants include:
math.pi:
Represents the mathematical constant π (pi).math.e:
Represents the mathematical constant e.
Here's an example that demonstrates the usage of some functions from the math
module:
import math
# Calculate the square root of a number
sqrt_result = math.sqrt(25)
print(sqrt_result) # Output: 5.0
# Calculate the sine of an angle in degrees
angle_degrees = 45
angle_radians = math.radians(angle_degrees)
sin_result = math.sin(angle_radians)
print(sin_result) # Output: 0.7071067811865476
# Calculate the factorial of a number
factorial_result = math.factorial(5)
print(factorial_result) # Output: 120
# Use mathematical constants
circle_area = math.pi * math.pow(2, 2)
print(circle_area) # Output: 12.566370614359172