The math
module in Python provides a wide range of mathematical functions and constants. Here are some methods and functionality of the math
module along with examples:
1. Basic Mathematical Functions:
math.sqrt(x)
: Return the square root of x
.
math.pow(x, y)
: Return x
raised to the power of y
.
math.exp(x)
: Return e
raised to the power of x
.
import math
result = math.sqrt(16)
print("Square Root:", result)
result = math.pow(2, 3)
print("2 raised to the power of 3:", result)
result = math.exp(2)
print("e raised to the power of 2:", result)
2. Trigonometric Functions:
math.sin(x)
, math.cos(x)
, math.tan(x)
: Trigonometric functions for sine, cosine, and tangent, respectively.
math.radians(x)
, math.degrees(x)
: Convert between radians and degrees.
import math
angle = math.radians(45)
sine_value = math.sin(angle)
print("Sine of 45 degrees:", sine_value)
3. Mathematical Constants:
math.pi
: The mathematical constant pi (π).
math.e
: The mathematical constant e.
import math
print("Value of pi:", math.pi)
print("Value of e:", math.e)
4. Logarithmic Functions:
math.log(x[, base])
: Return the natural logarithm of x
. Optionally, specify a base for the logarithm.
import math
result = math.log(10)
print("Natural Logarithm of 10:", result)
result = math.log(100, 10)
print("Base-10 Logarithm of 100:", result)
5. Rounding and Ceiling/Floor Functions:
math.ceil(x)
: Return the smallest integer greater than or equal to x
.
math.floor(x)
: Return the largest integer less than or equal to x
.
math.trunc(x)
: Return the integer value of x
(truncate decimal part).
import math
ceil_value = math.ceil(4.3)
print("Ceil(4.3):", ceil_value)
floor_value = math.floor(4.7)
print("Floor(4.7):", floor_value)
trunc_value = math.trunc(5.9)
print("Trunc(5.9):", trunc_value)
6. Other Functions:
math.factorial(x)
: Return the factorial of x
.
math.gcd(a, b)
: Return the greatest common divisor of two integers a
and b
.
import math
factorial = math.factorial(5)
print("Factorial of 5:", factorial)
gcd_value = math.gcd(24, 36)
print("GCD of 24 and 36:", gcd_value)
These are some of the methods and functionality provided by the math module in Python. It's a powerful tool for performing mathematical calculations in your Python scripts.