On this page
  1. math
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Safe Floating-Point Comparison & Validation (isclose, isfinite)
  7. 2. Integer Geometry & Exact Combinatorics
  8. Gotchas & Boundaries
  9. Common Functions
  10. Constants & Attributes

math

Prev: marshal | Up: stdlib_module | Next: mimetypes
Rel: numbers, cmath, decimal, fractions, random
Ref: docs.python.org — math
Tags: #public #python3 #stdlib


Import

import math

Overview

C-speed real-number mathematical functions (sqrt, isqrt, floor, ceil, log, exp, sin, cos, comb, perm, gcd, lcm, prod, isclose, isfinite) and constants (pi, e, tau, inf, nan). Use math for scalar floating-point and integer math; use decimal for exact currency, statistics for descriptive stats, and cmath for complex numbers.

Quick Start

import math

assert math.isclose(0.1 + 0.2, 0.3)
assert math.isqrt(26) == 5
assert math.gcd(24, 36) == 12
assert math.comb(5, 2) == 10
assert math.prod([2, 3, 4]) == 24

Implementation Walkthrough

1. Safe Floating-Point Comparison & Validation (isclose, isfinite)

Never compare computed floats with ==; use math.isclose() with explicit relative/absolute tolerances, and guard against NaN/inf with math.isfinite():

import math

def safe_normalize(values: list[float]) -> list[float]:
    if not values or not all(math.isfinite(v) for v in values):
        raise ValueError("All values must be finite numbers")
    total = math.fsum(values)  # high-precision summation
    if math.isclose(total, 0.0, abs_tol=1e-12):
        raise ValueError("Sum is zero")
    return [v / total for v in values]

res = safe_normalize([0.1, 0.2, 0.7])
assert math.isclose(math.fsum(res), 1.0)

2. Integer Geometry & Exact Combinatorics

import math

assert math.hypot(3, 4) == 5.0
assert math.dist((0, 0), (3, 4)) == 5.0
assert math.lcm(12, 18) == 36

Gotchas & Boundaries

Common Functions

Constants & Attributes

Linked from

Related notes