Math & Statistical Computations
Perform precision math operations, analyze datasets with mean and median, and calculate variance.
IEEE 754 Floating-Point Precision & math.isclose()
Computers store numbers in binary. Just as 1/3 cannot be represented in finite decimal digits, fractions like 0.1 cannot be represented in finite binary digits. This means 0.1 + 0.2 == 0.3 evaluates to False — the actual stored value is 0.30000000000000004.
Comparing floats with == is a critical bug. Always use math.isclose(a, b, rel_tol=1e-9) to check equality within a numerical tolerance instead.
The statistics module is an automated accountant — finding averages, medians, and variance across numbers in a single call, without manually tallying anything by hand.
Safe Floating-Point Comparisons with math.isclose
Run the snippet below to see why direct float equality fails and how math.isclose() fixes it:
import math
a = 0.1 + 0.2
b = 0.3
print("Direct equality (a == b):", a == b)
print("Actual evaluated value of a:", repr(a))
print("Safe comparison with math.isclose:", math.isclose(a, b))
# Custom tolerance testing (e.g. within 1 cent)
price_a = 19.991
price_b = 19.994
print("Within 1 cent?", math.isclose(price_a, price_b, abs_tol=0.01))Safely compares two floats within a relative or absolute tolerance margin.
Fixed-point base-10 arithmetic for audit-grade financial calculations.
Three distinct rounding directions: toward -inf, toward +inf, and toward zero.
The middle value of a dataset — resilient to outliers, unlike the mean.
Trace How Each Technique Works
Click through each technique to see its exact behavior:
Binary floating-point cannot represent 0.1 or 0.2 exactly. Direct == comparison is a critical bug; math.isclose() checks equality within a tolerance instead.
Precision, Primitives, and Descriptive Statistics
These three families cover exact arithmetic, general-purpose math primitives, and dataset analysis.
Precision & exact arithmetic
math.isclose(a, b, rel_tol=1e-9)Safely compares two floats within a relative/absolute tolerance.
Decimal("0.10")Construct from a string to avoid inheriting binary float rounding error.
d.quantize(Decimal('0.01'), rounding=...)Rounds a Decimal to a fixed number of places with an explicit rounding mode.
math module primitives
math.floor(x) / math.ceil(x)Round down toward -inf / up toward +inf.
math.trunc(x)Discards the fractional part, rounding toward zero.
math.gcd(a, b) / math.lcm(a, b)Greatest common divisor / least common multiple.
math.comb(n, k) / math.perm(n, k)Combinatorics: combinations and permutations.
statistics module
statistics.mean(data) / fmean(data)Arithmetic mean; fmean() is a faster floating-point variant.
statistics.median(data) / mode(data)Middle value; most frequently occurring value.
statistics.stdev(data) / variance(data)Sample standard deviation and variance of a dataset.
statistics.quantiles(data, n=4)Splits a dataset into n evenly-spaced percentile cut points.
Worked Hands-on Walkthroughs
Progress step-by-step from safe float comparisons, through exact financial arithmetic, to analyzing real latency data:
Safe Floating-Point Comparisons with math.isclose
math.isclose safely evaluates floating-point equality without suffering from binary fraction discrepancies.
import math
a = 0.1 + 0.2
b = 0.3
print("Direct equality (a == b):", a == b)
print("Actual evaluated value of a:", repr(a))
print("Safe comparison with math.isclose:", math.isclose(a, b))
# Custom tolerance testing (e.g. within 1 cent)
price_a = 19.991
price_b = 19.994
print("Within 1 cent?", math.isclose(price_a, price_b, abs_tol=0.01))math.isclose safely evaluates floating-point equality without suffering from binary fraction discrepancies.
Financial Ledger Calculations with decimal.Decimal
Decimal provides deterministic, audit-grade arithmetic with customizable rounding modes.
from decimal import Decimal, ROUND_HALF_UP
# Construct from strings to guarantee exact base-10 values!
item_price = Decimal("19.99")
tax_rate = Decimal("0.0825") # 8.25% tax
raw_tax = item_price * tax_rate
print("Exact calculated tax:", raw_tax)
# Quantize to 2 decimal places using standard financial rounding
final_tax = raw_tax.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
total = item_price + final_tax
print("Rounded Tax:", final_tax)
print("Total Invoice:", total)Decimal provides deterministic, audit-grade arithmetic with customizable rounding modes.
Analyzing System Latencies with the statistics Module
Because of the single 120ms spike, the mean is skewed to 57ms, while the median (50.5ms) represents typical user experience.
import statistics
# Web request response times in milliseconds
latencies = [45, 52, 48, 120, 55, 49, 51, 50, 48, 52]
mean_lat = statistics.mean(latencies)
median_lat = statistics.median(latencies)
stdev_lat = statistics.stdev(latencies)
quartiles = statistics.quantiles(latencies, n=4)
print(f"Average Latency: {mean_lat:.1f} ms")
print(f"Median Latency: {median_lat:.1f} ms")
print(f"Standard Dev: {stdev_lat:.2f} ms")
print(f"Quartiles (Q1, Q2, Q3): {[round(q, 1) for q in quartiles]}")Because of the single 120ms spike, the mean is skewed to 57ms, while the median (50.5ms) represents typical user experience.
Common Traps & How to Avoid Them
Study the mistakes and clean fixes below before relying on numerical calculations in production:
# Mistyped variable or missing closing parenthesis
result = math___statistical_analysis_val# Declare and verify variables before execution
val = 10
print("Defined correctly:", val)Beginners frequently encounter typos or forgotten definitions before using an identifier.
# Modifying shared state or unexpected variable shadowing
def update_state(data=[]):
data.append(1)
return datadef update_state(data=None):
if data is None:
data = []
data.append(1)
return dataDefault arguments in Python are evaluated once at function definition time, not at invocation time.
# Opening resources in a tight loop without closing or bounding memory
files = [open(f"log_{i}.txt", "w") for i in range(5000)]for i in range(5):
with open(f"log_{i}.txt", "w") as f:
f.write("Safe")Failing to release system resources leads to process termination under heavy production workloads.
Real-World Systems in Action
See how scripts, backend services, and SRE monitoring pipelines all rely on precise numerical computation at scale:
Local Developer Automation Tool
Individual developers and IT administrators automate everyday repetitive workflows.
A clean standalone script providing fast, local automation with zero dependencies.
import statistics
latency_ms = [45, 52, 48, 120, 50, 47]
print("Median latency:", statistics.median(latency_ms))
print("Mean latency:", round(statistics.mean(latency_ms), 1))Backend API Service Integration
SaaS platforms run backend microservices processing requests concurrently.
A modular service handler integrating validation and structured responses.
# Service integration layer
def handle_request(payload: dict) -> dict:
return {"status": "success", "processed": True}High-Throughput Cloud Architecture
Site reliability engineering (SRE) monitoring agents compute p50, p90, and p99 service latencies to trigger automated auto-scaling.
Site reliability engineering (SRE) monitoring agents compute p50, p90, and p99 service latencies to trigger automated auto-scaling.
# High-resilience production pattern
import time
def process_stream(events: list) -> int:
processed = 0
for event in events:
if event:
processed += 1
return processedKey Points & Concept Review
- Never compare floating-point numbers with ==; use math.isclose(a, b).
- Use decimal.Decimal constructed from strings for financial and banking calculations.
- math.floor rounds down towards -inf; math.trunc rounds towards zero.
- math.gcd and math.lcm simplify number-theoretic calculations.
- The statistics module provides robust metrics: mean, median, multimode, stdev, and quantiles.
- The median is resilient against anomalous outliers, whereas the mean reflects aggregate volume.
Frequently Asked Questions & Reference Hub
Comparing two floats? Reach for math.isclose(). Handling money? Reach for decimal.Decimal. Summarizing a dataset? Reach for the statistics module. Matching the tool to the question prevents an entire category of subtle numerical bugs before they ever ship.
Understand why direct float equality checks are unreliable.
Reference ROUND_HALF_UP and other rounding strategies.
See how the three rounding directions diverge on negatives.
Learn why the median resists skew from anomalous data points.
Understand how quantiles() splits a dataset into percentiles.
Deep dive into why 0.1 + 0.2 != 0.3 at the hardware level.
You've Mastered Math & Statistical Computations!
You understand math.isclose(), decimal.Decimal, floor/ceil/trunc, gcd/lcm, and the statistics module. Now lock in your knowledge with hands-on practice.
Compute the mean and median of a scores dataset and format the output exactly.
Earn experience points toward your developer rank as soon as you pass.
Bite-sized knowledge check with instant explanations for every question.
Worked example
Compute the average of test scores with statistics.mean.
import statistics print(int(statistics.mean([10, 20, 30])))
How it works, step by step
- statistics.mean computes the arithmetic average.
Math & Statistical Computations practice
Given exam marks scores = [70, 85, 90, 75, 80], calculate the mean and median using the statistics module. Print: Mean: 80.0, Median: 80.
Coding Practice is Locked
Sign in to access the interactive Python editor, write and run code checks against automated tests, use hints, and earn XP.
Practice quiz
Check yourself
15 questions with explanations after submission, so you can correct course as you go.
Math & Statistical Computations quiz
LockedYou must be signed in to take this quiz. Sign in to test your understanding, track your answers, and earn XP.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.