Python Math
Python provides a built-in module called math
that offers various mathematical operations and functions. You can import the math
module at the beginning of your code like this:
python
import math
Once you have imported the math
module, you can use its functions and constants to perform mathematical calculations. Here are some commonly used functions and constants from the math
module:
- Mathematical Constants:
math.pi
: Represents the mathematical constant π (pi).math.e
: Represents the mathematical constant e (Euler’s number).
- Basic Mathematical Functions:
math.sqrt(x)
: Returns the square root of x.math.pow(x, y)
: Returns x raised to the power y.math.exp(x)
: Returns e raised to the power x.math.log(x, base)
: Returns the logarithm of x to the given base (default is natural logarithm).math.log10(x)
: Returns the base-10 logarithm of x.math.ceil(x)
: Returns the smallest integer greater than or equal to x.math.floor(x)
: Returns the largest integer less than or equal to x.math.trunc(x)
: Returns the truncated integer value of x (removes the decimal part).
- Trigonometric Functions:
math.sin(x)
: Returns the sine of x (x is in radians).math.cos(x)
: Returns the cosine of x (x is in radians).math.tan(x)
: Returns the tangent of x (x is in radians).math.radians(degrees)
: Converts degrees to radians.math.degrees(radians)
: Converts radians to degrees.
- Other Functions:
math.factorial(x)
: Returns the factorial of x.math.gcd(x, y)
: Returns the greatest common divisor of x and y.math.isclose(a, b, rel_tol=1e-09, abs_tol=0.0)
: Returns True if the values a and b are close to each other within the specified tolerance.
These are just a few examples of the functions and constants provided by the math
module. You can explore more by referring to the Python documentation for the math
module: math — Mathematical functions