Math in Python
Python provides a built-in math library called math that contains a set of mathematical functions and constants for performing tasks on numbers.
To use the math module, you need to import it first. For example:
import math
Here are some of the most commonly used functions from the math library:
- Basic Mathematical Functions:
- Trigonometric Functions:
- Hyperbolic Functions:
- Ceil and Floor Functions:
- Constants:
Here's an example to demonstrate how Python's math module can be used for some common mathematical calculations:
import math
x = 32
y = 10
base = 2
a = math.sqrt(x) #Returns the square root of x.
b = math.exp(x) #Returns the exponential of x (e^x).
c = math.log(x, base) #Returns the natural logarithm (base e) of x or the logarithm of x with the specified base.
d = math.pow(x, y) #Returns x raised to the power of y.
print(a)
print(b)
print(c)
print(d)
Here's an example to show how Python's math module can be used for some common trigonometric calculations:
import math
x = 90
a = math.sin(x) # Returns the sine of x, where x is in radians.
b = math.cos(x) # Returns the cosine of x, where x is in radians.
c = math.tan(x) # Returns the tangent of x, where x is in radians.
d = math.radians(x) # Converts degrees to radians.
e = math.degrees(x) # Converts radians to degrees.
print(a)
print(b)
print(c)
print(d)
print(e)
Here's an example to show how Python's math module can be used for some common hyberbolic calculations:
import math
x = 90
a = math.sinh(x) # Returns the hyperbolic sine of x.
b = math.cosh(x) # Returns the hyperbolic cosine of x.
c = math.tanh(x) # Returns the hyperbolic tangent of x.
print(a)
print(b)
print(c)
The ceil() function rounds a number up to its nearest integer, whereas the floor() function rounds a number down to its nearest integer. For example:
import math
x = 90.689
a = math.ceil(x) # Returns the smallest integer greater than or equal to x.
b = math.floor(x) # Returns the largest integer less than or equal to x.
print(a)
print(b)
The Python math module also provides mathematical constants such as pi and Euler's number (e). For example:
import math
a = math.pi # The mathematical constant π (pi).
b = math.e # The mathematical constant e (Euler's number).
print(a)
print(b)