Python math module
The math
module in Python provides a wide range of mathematical functions and constants that are useful for performing complex mathematical operations. It is part of the standard library, which means you can use it without any additional installations.
Importing the Math Module
To use the functions in the math
module, you need to import it:
Key Functions and Constants
Mathematical Constants:
math.pi
: The mathematical constant π (pi), approximately 3.14159.math.e
: The mathematical constant e (Euler's number), approximately 2.71828.
Basic Functions:
math.ceil(x)
: Returns the smallest integer greater than or equal tox
.math.floor(x)
: Returns the largest integer less than or equal tox
.
Power and Logarithmic Functions:
math.sqrt(x)
: Returns the square root ofx
.math.pow(x, y)
: Returnsx
raised to the power ofy
.math.log(x[, base])
: Returns the logarithm ofx
to the specified base (default ise
).
Trigonometric Functions:
math.sin(x)
: Returns the sine ofx
(x in radians).math.cos(x)
: Returns the cosine ofx
.math.tan(x)
: Returns the tangent ofx
.
Angle Conversion:
math.radians(x)
: Converts degrees to radians.math.degrees(x)
: Converts radians to degrees.
Factorial and Combinatorial Functions:
math.factorial(x)
: Returns the factorial ofx
(x must be a non-negative integer).math.comb(n, k)
: Returns the number of ways to choosek
items fromn
items without repetition.math.perm(n, k)
: Returns the number of ways to choosek
items fromn
items with repetition.
Hyperbolic Functions:
math.sinh(x)
: Returns the hyperbolic sine ofx
.math.cosh(x)
: Returns the hyperbolic cosine ofx
.math.tanh(x)
: Returns the hyperbolic tangent ofx
.
Other Functions:
math.isqrt(x)
: Returns the integer square root ofx
.math.gcd(x, y)
: Returns the greatest common divisor ofx
andy
.math.dist(p, q)
: Returns the Euclidean distance between pointsp
andq
.
Example Usage
Here’s an example demonstrating the use of several functions from the math
module:
Summary
- The
math
module provides a variety of mathematical functions and constants. - Useful for performing complex mathematical operations like trigonometry, logarithms, and combinatorial calculations.
- Functions can be used with integers and floating-point numbers, making it a versatile module for mathematical computations.