The Python math library is a built-in module that provides access to a wide range of mathematical functions and constants, making it essential for scientific computing, data analysis, and engineering applications.
Key Features
Built-in and No Installation Required: The
mathmodule is part of Python’s standard library, so you don’t need to install it separately. Simply import it using:import mathCommon Constants:
math.pi: Returns the value of π (3.141592653589793).math.e: Returns Euler’s number (2.718281828459045).
Core Mathematical Functions:
Trigonometry:
math.sin(),math.cos(),math.tan(), and their inverse/hyperbolic variants (asin,acosh, etc.).Logarithms:
math.log(),math.log10(),math.log2(), andmath.log1p()for precise computation near zero.Exponentials:
math.exp(),math.pow(), andmath.expm1()for accurate results with small values.Rounding:
math.ceil(),math.floor(),math.trunc(), andmath.isclose()for comparing floating-point numbers.Roots & Powers:
math.sqrt(),math.pow(), andmath.isqrt()for integer square roots.Factorial:
math.factorial(n)computes the factorial of a non-negative integer.GCD & LCM:
math.gcd(a, b)andmath.lcm(*integers)for number theory tasks.Miscellaneous:
math.fabs(),math.fsum(),math.dist(),math.comb(),math.perm().
Usage Example
import math
# Calculate area of a circle
radius = 5
area = math.pi * math.pow(radius, 2)
print(f"Area: {area}")
# Compute factorial
print(f"Factorial of 5: {math.factorial(5)}")
# Convert degrees to radians and compute sine
angle_deg = 45
angle_rad = math.radians(angle_deg)
print(f"Sin(45°): {math.sin(angle_rad)}")Best Practices
Use
from math import sqrt, pito avoid prefixing every function call.Always check input validity (e.g.,
math.sqrt()raisesValueErrorfor negative numbers).For array-based operations, consider using NumPy instead of
mathfor better performance.
The math module is reliable, efficient, and ideal for precise mathematical computations in Python.