Python Math Module: Functions for AI & ML

Explore Python's math module for AI & ML. Learn how to import and use functions for real number operations, essential for data science and machine learning.

5.3 Python Math Module

The math module in Python provides access to mathematical functions defined by the C standard. It supports operations on real numbers (integers and floats). For complex numbers, the cmath module should be used instead.

Importing the Math Module

Before using any of the mathematical functions, you need to import the module:

import math

Categories of Math Module Functions

The math module can be broadly categorized into several groups of functions:

1. Theoretic and Representation Functions

These functions handle basic numeric operations such as rounding, absolute values, number theory, and decompositions.

FunctionDescription
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.fabs(x)Returns the absolute value of x as a float.
math.factorial(n)Returns the factorial of n.
math.trunc(x)Truncates the decimal and returns the integer part.
math.modf(x)Splits x into fractional and integer parts as a tuple.
math.frexp(x)Returns the mantissa and exponent of x as a tuple (m, e).
math.ldexp(x, i)Computes x * (2**i).
math.fmod(x, y)Returns the remainder of x divided by y (IEEE 754 style).
math.remainder(x, y)Returns the IEEE remainder of x with respect to y.
math.isclose(a, b)Returns True if a and b are close in value.
math.isfinite(x)Returns True if x is a finite number.
math.isinf(x)Returns True if x is positive or negative infinity.
math.isnan(x)Returns True if x is NaN (Not a Number).
math.gcd(*integers)Computes the greatest common divisor of the specified integers.
math.lcm(*integers)Computes the least common multiple of the specified integers.
math.isqrt(n)Returns the integer square root of n.
math.copysign(x, y)Returns x with the sign of y.
math.ulp(x)Returns the unit in the last place of x.
math.perm(n, k)Calculates the number of permutations (nPk).
math.comb(n, k)Calculates the number of combinations (nCk).
math.prod(iterable)Returns the product of all elements in an iterable.
math.nextafter(x, y)Returns the next floating-point number after x toward y.

2. Power and Logarithmic Functions

These functions are useful for exponential, root, and logarithmic calculations.

FunctionDescription
math.pow(x, y)Returns x raised to the power y.
math.sqrt(x)Returns the square root of x.
math.cbrt(x)Returns the cube root of x.
math.exp(x)Returns e raised to the power x.
math.exp2(x)Returns 2 raised to the power x.
math.expm1(x)Returns e**x - 1 (accurate for small x).
math.log(x)Natural logarithm of x (base e).
math.log10(x)Logarithm of x with base 10.
math.log2(x)Logarithm of x with base 2.
math.log1p(x)Computes log(1 + x) accurately for small x.

3. Trigonometric Functions

All trigonometric functions work with angles measured in radians.

FunctionDescription
math.sin(x)Returns the sine of x (in radians).
math.cos(x)Returns the cosine of x (in radians).
math.tan(x)Returns the tangent of x (in radians).
math.asin(x)Returns the arc sine of x (in radians).
math.acos(x)Returns the arc cosine of x (in radians).
math.atan(x)Returns the arc tangent of x (in radians).
math.atan2(y, x)Returns atan(y / x) with correct quadrant.
math.hypot(x, y)Returns the Euclidean norm sqrt(x² + y²).

4. Angular Conversion Functions

Use these functions to convert between degrees and radians.

FunctionDescription
math.degrees(x)Converts radians to degrees.
math.radians(x)Converts degrees to radians.

5. Hyperbolic Functions

Hyperbolic versions of trigonometric functions, often used in calculus and geometry.

FunctionDescription
math.sinh(x)Returns the hyperbolic sine of x.
math.cosh(x)Returns the hyperbolic cosine of x.
math.tanh(x)Returns the hyperbolic tangent of x.
math.asinh(x)Returns the inverse hyperbolic sine.
math.acosh(x)Returns the inverse hyperbolic cosine.
math.atanh(x)Returns the inverse hyperbolic tangent.

6. Special Functions

These functions are typically used in advanced mathematics and statistics.

FunctionDescription
math.erf(x)Error function.
math.erfc(x)Complementary error function.
math.gamma(x)Gamma function, an extension of factorial.
math.lgamma(x)Natural logarithm of the absolute value of gamma.

Mathematical Constants in the Math Module

The math module also provides several useful mathematical constants:

ConstantDescription
math.piThe value of π (approximately 3.14159).
math.eEuler’s number (approximately 2.71828).
math.tauTau (2π, approximately 6.28318).
math.infPositive infinity.
-math.infNegative infinity.
math.nanNot a Number (NaN).

Example Usage of the Math Module

Here are a few real-world examples that demonstrate the use of common math functions:

import math

# Square root
print(f"Square root of 16: {math.sqrt(16)}") # Output: 4.0

# Factorial
print(f"Factorial of 5: {math.factorial(5)}") # Output: 120

# Logarithm base 10
print(f"Logarithm base 10 of 100: {math.log10(100)}") # Output: 2.0

# Power
print(f"2 raised to the power of 3: {math.pow(2, 3)}") # Output: 8.0

# Greatest Common Divisor
print(f"GCD of 18 and 24: {math.gcd(18, 24)}") # Output: 6

# Trigonometric function (cosine of 60 degrees)
print(f"Cosine of 60 degrees: {math.cos(math.radians(60))}") # Output: 0.5

# Ceiling and Floor
print(f"Ceiling of 4.2: {math.ceil(4.2)}") # Output: 5
print(f"Floor of 4.7: {math.floor(4.7)}") # Output: 4

# Absolute value
print(f"Absolute value of -10.5: {math.fabs(-10.5)}") # Output: 10.5

# Check for infinity
print(f"Is math.inf finite? {math.isfinite(math.inf)}") # Output: False

Conclusion

The Python math module is an essential tool for performing numeric computations efficiently. Whether you’re a beginner or an experienced developer, knowing how to leverage these functions can simplify your mathematical programming tasks significantly.

For advanced operations involving complex numbers, use the cmath module instead. For statistical functions, consider using libraries like statistics, numpy, or scipy.