Python provides a built-in or pre-installed math module. We just need to import it into the program where we want to use it.
The "math" module in Python provides access to mathematical functions and constants.
We can import the `math` module, like other modules we import from Python, the `math` module helps in implementing the functions to perform mathematical operations.
Common functions and constants available in the "math" module:
Returns the square root of x.
import math print(math.sqrt(49)) # Output: 7.0
Returns x raised to the power of y.
import math print(math.pow(4, 3)) # Output: 64.0
Returns the exponential of x (e^x).
import math print(math.exp(10)) # Output: 22026.465794806718
Converts angle x from radians to degrees, and vice versa.
import math print(math.degrees(math.pi)) # Output: 180.0 print(math.radians(180)) # Output: 3.141592653589793
Returns the "sine", "cosine", and "tangent" of x (in radians), respectively.
import math print(math.sin(math.pi / 2)) # Output: 1.0 print(math.cos(0)) # Output: 1.0 print(math.tan(math.pi / 4)) # Output: 1.0
Returns the ceiling and floor of num, respectively (the smallest integer greater than or equal to num, and the largest integer less than or equal to num).
import math print(math.ceil(7.2)) # Output: 7 print(math.floor(7.7)) # Output: 8
Returns the factorial of `num`.
import math print(math.factorial(4)) # Output: 24
A constant representing the mathematical constant π (pi).
import math print(math.pi) # Output: 3.141592653589793
A constant representing the mathematical constant e (Euler's number).
import math print(math.e) # Output: 2.718281828459045
The `math.nan` gives us the `nan` (Not a Number) value. It Indicates that the value is not a valid numeric value. Data Type of `nan` is Float Type.
# Import math module import math # print the nan value using the `math` module print(math.nan) # Output: nan print(type(math.nan)) # Output: <class 'float'>
These are just a few examples of what we can do with the math module.
There are many more functions available for various mathematical operations.
Always ensure to import the math module (import math) before using its functions.