The math module in Python provides access to a wide range of mathematical functions and constants. It's extremely useful when working with more advanced numerical calculations beyond basic arithmetic. Before using any functions from the module, you need to import it at the top of your script:
import math
Then you can access the functions and constants. Some of the most useful are:
| Function or Constant | Description |
|---|---|
math.pi
|
The value of π (3.14159...) |
math.e
|
The value of Euler's number (≈2.718) |
math.sqrt(x)
|
Returns the square root of x |
math.pow(x, y)
|
Returns x raised to the power y |
math.floor(x)
|
Rounds down to the nearest whole number |
math.ceil(x)
|
Rounds up to the nearest whole number |
math.trunc(x)
|
Truncates decimal (just keeps the integer part) |
math.fabs(x)
|
Returns the absolute value (always positive) |
math.factorial(x)
|
Returns the factorial of x |
math.log(x)
|
Returns natural logarithm (base e) |
math.log10(x)
|
Logarithm base 10 |
math.sin(x) / math.cos(x) / math.tan(x)
|
Trigonometric functions (input in radians) |
math.degrees(x)
|
Converts radians to degrees |
math.radians(x)
|
Converts degrees to radians |
math.isclose(a, b)
|
Checks if two numbers are close in value |
math.gcd(a, b)
|
Finds the greatest common divisor of a and b |