← Back to Chapters

Python Math Module

? Python Math Module

⚡ Quick Overview

The math module in Python provides access to many common mathematical functions and constants like pi, e, trigonometric functions, logarithms, rounding helpers, and more. It is ideal for scientific calculations, geometry, statistics, and any program that needs precise math.

To use it, you must first import it: import math

? Key Concepts

  • Import the module once using import math.
  • Access constants like math.pi and math.e.
  • Use trigonometric functions (sin, cos, tan) with angles in radians.
  • Work with exponentials and logarithms using exp, log, and log10.
  • Round numbers with ceil, floor, and get absolute values with fabs.
  • Perform basic math operations like sum, product, square root using fsum, prod, sqrt.
  • Convert between degrees and radians with radians and degrees.
  • Use special helpers like factorial, gcd, isfinite, isinf, and isnan.

? Syntax and Usage

Basic import and usage pattern:

import math

# syntax: math.function_name(arguments)
result = math.sqrt(25)
print(result)

Every function and constant in this module is accessed using the math. prefix, which clearly shows it comes from the math library and avoids name clashes with your own variables.

? Code Examples

? Importing the Math Module & Constants

? View Code Example
import math

print(math.pi)       # 3.141592653589793
print(math.e)        # 2.718281828459045

? Trigonometric Functions (Angles in Radians)

Trigonometric functions in math expect angles in radians, not degrees.

? View Code Example
import math

angle = math.pi / 4  # 45 degrees in radians
print(math.sin(angle))   # 0.7071067811865475
print(math.cos(angle))   # 0.7071067811865476
print(math.tan(angle))   # 0.9999999999999999

? Exponential & Logarithmic Functions

? View Code Example
import math

print(math.exp(2))        # e^2 ≈ 7.38905609893065
print(math.log(math.e))   # 1.0 (natural log, base e)
print(math.log10(100))    # 2.0 (base 10)
print(math.pow(3, 3))     # 27.0 (always returns float)

? Rounding & Absolute Value

? View Code Example
import math

print(math.ceil(4.2))   # 5  (round up)
print(math.floor(4.8))  # 4  (round down)
print(math.fabs(-5.5))  # 5.5 (float absolute value)

? Basic Calculations: Sum, Product, Square Root

? View Code Example
import math

nums = [4, 7, 1, 9]
print(math.fsum(nums))   # 21.0 (accurate sum of floats)
print(math.prod(nums))   # 252 (product of numbers)
print(math.sqrt(16))     # 4.0 (square root)

? Angle Conversions

? View Code Example
import math

print(math.radians(180))     # 3.141592653589793 (degrees → radians)
print(math.degrees(math.pi)) # 180.0 (radians → degrees)

✅ Special Functions

? View Code Example
import math

print(math.factorial(5))      # 120
print(math.gcd(12, 18))       # 6
print(math.isfinite(10/3))    # True
print(math.isinf(math.inf))   # True
print(math.isnan(float("nan")))  # True

? Live Output & Explanation

If you run all the code examples above together, you will see:

  • High-precision values for pi and e.
  • Trigonometric values very close to their theoretical values (like sin(π/4) ≈ 0.7071).
  • Exponential and logarithmic results that match basic math rules (e.g. log(e) = 1).
  • Rounded values from ceil and floor and an always-positive result from fabs.
  • Accurate sum and product of lists using fsum and prod.
  • Correct angle conversions between degrees and radians.
  • Special checks like isfinite, isinf, and isnan giving boolean answers.

These utilities make the math module powerful and convenient for numerical programs where precision and reliability matter.

? Tips & Best Practices

  • Always remember that trigonometric functions in math use radians. Convert degrees using math.radians().
  • Use math.fsum() instead of the built-in sum() when summing many floating-point numbers for better precision.
  • math.factorial() only accepts non-negative integers. Passing a negative or non-integer value will raise a ValueError.
  • math.prod() is a clean way to compute the product of items in an iterable like a list or tuple.
  • math.sqrt(x) requires x ≥ 0. For complex square roots (like √−1), use the cmath module.
  • Prefer math.pow(a, b) when you specifically want a floating-point result; otherwise the ** operator is often faster.

? Try It Yourself

  • Calculate the sin, cos, and tan of 60 degrees (hint: convert to radians first).
  • Find the factorial of 7 and the product of the numbers [2, 3, 4] using math.factorial() and math.prod().
  • Convert 90 degrees to radians using math.radians() and then convert math.pi / 2 back to degrees.
  • Compute the GCD of 56 and 98 using math.gcd().
  • Use math.fsum() to sum [0.1, 0.2, 0.3] and compare it with sum([0.1, 0.2, 0.3]).