Python Math

Tutorial 27 of 65 · pythondeck.com Python course

The standard math module covers floats: trig, log, exp, gamma, gcd, hypot, isclose. statistics provides mean/median/stdev; random generates pseudo-random numbers; cmath handles complex numbers.

Python's numeric tower spans integers (unlimited precision), floats (IEEE binary), decimals, and fractions. The math module is for float trigonometry and special functions; statistics summarises data; random samples distributions; cmath extends to complex numbers.

Floating-point equality is approximate: use math.isclose() with suitable tolerances. For money or legal rounding, consider decimal.Decimal instead of binary floats.

Angles in math use radians; convert degrees with math.radians before calling trig functions to avoid silent wrong answers in geometry code.

math: sqrt, log, sin, hypot, isclose, gcd.

statistics: mean, median, mode, variance, stdev (population vs sample).

random: random(), randint, choice, shuffle, seeds and secrets for security.

Complex numbers: 1+2j, cmath, and built-in abs / phase patterns.

NumPy for vectorised arrays (optional, when scale demands it).

Infinity, NaN, and math.isfinite for edge-case checks.

The ** operator and pow() handle integer exponentiation efficiently; math.pow always returns a float. For modular exponentiation in cryptography, use pow(base, exp, mod).

Random numbers from random are pseudo-random and not suitable for passwords or tokens—use the secrets module. Reproducible simulations need an explicit random.seed() or a dedicated random.Random instance.

When datasets grow large, pure-Python loops over math functions become bottlenecks; NumPy or Numba may be warranted, but profile first.

Comparing floats with == without tolerance.

Using random for security-sensitive tokens or session IDs.

Confusing population and sample standard deviation in statistics.stdev vs pstdev.

Integer division confusion: / vs // vs %.

Overflow silently becoming float for very large ints only when mixed with floats in expressions.

Use math.isclose or decimal arithmetic for financial and scientific comparisons.

Pick statistics functions that match your data (sample vs population).

Seed random generators explicitly in notebooks and tests for reproducibility.

Profile before replacing stdlib math with NumPy in hot loops.

Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.

The program below demonstrates math basics. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# Example: math basics
# Run in the REPL or save as a .py file and execute with python.
import math
print(math.pi, math.e)
print(math.sqrt(2), math.log(math.e))

This sample walks through isclose in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# Example: isclose
# Run in the REPL or save as a .py file and execute with python.
import math
print(0.1 + 0.2 == 0.3)             # False!
print(math.isclose(0.1 + 0.2, 0.3))   # True

Here is a hands-on illustration of statistics. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.

# Example: statistics
# Run in the REPL or save as a .py file and execute with python.
import statistics as st
v = [2, 4, 4, 4, 5, 5, 7, 9]
print(st.mean(v), st.median(v), round(st.stdev(v), 2))

The program below demonstrates math constants. Read the comments on each line, run the code, then change names or values to see how the output shifts.

# math module wraps C floating-point math functions
import math  # standard math functions
print(math.pi, math.tau)  # circle constants
print(math.sqrt(2), math.hypot(3, 4))  # root and hypotenuse
angle = math.radians(45)  # degrees -> radians
print(math.sin(angle), math.cos(angle))  # trig
print(math.log(100, 10))  # base-10 logarithm -> 2.0
print(math.factorial(6))  # 720
print(math.gcd(48, 18))  # greatest common divisor
print(math.isclose(0.1 + 0.2, 0.3))  # tolerant float compare

This sample walks through statistics sample in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.

# statistics module targets simple descriptive stats
import statistics as stats  # mean/median/stdev helpers
samples = [2.5, 3.1, 2.9, 3.0, 2.8]  # measurements
print(stats.mean(samples))  # arithmetic mean
print(stats.median(samples))  # middle value
print(stats.pstdev(samples))  # population stdev
print(stats.quantiles(samples, n=4))  # quartile cut points
import random  # pseudo-random numbers
random.seed(0)  # reproducible sequence
print(random.random(), random.randint(1, 6))  # float and int

« Python Dates All tutorials Python JSON »