Python Math Module
Python provides a built-in math
module which provides a set of mathematical functions. These functions are not readily available in Python's global namespace and can be accessed only after importing the math
module.
Syntax
To use the functions provided by the math module, you need to import the math module first using the following statement.
import math
To call a function from the math
module, use the dot notation:
math.function_name()
Example
import math
# finding square root of a number
print(math.sqrt(25))
# angle in radians
print(math.radians(30))
# sine of 60 degrees
print(math.sin(math.radians(60)))
Output
5.0
0.5235987755982988
0.8660254037844386
Explanation
math.sqrt()
- returns the square root of the specified number.math.radians()
- converts the angle from degrees to radians before passing it to trigonometric functions such assin()
,cos()
, etc.math.sin()
- returns the sine of the angle passed in radians.
Use
The math
module is useful in mathematical calculations involved in various fields such as statistics, physics, and engineering. It provides more precise and accurate results as compared to the Python's built-in arithmetic operators.
Important Points
- All functions in the
math
module accept only numeric arguments and return numeric values. - Some of the most commonly used functions include
sqrt()
,sin()
,cos()
,tan()
,log()
,exp()
,ceil()
,floor()
, etc. - Before using the
math
module, ensure that you have imported it using the statementimport math
. - If you try to use a function without importing the
math
module, Python will raise aNameError
.
Summary
In this tutorial, we learned about the math
module in Python. It provides a set of mathematical functions that are not available in Python's global namespace. We learned how to import the module, call different functions, and also saw examples of some commonly used functions.