Skip to contentSkip to navigation
MODULE 11 · LESSON 06

Math & Statistical Computations

Perform precision math operations, analyze datasets with mean and median, and calculate variance.

Core Learning Milestones:
math.isclose()
Safe float comparison
decimal.Decimal
Exact base-10 arithmetic
floor / ceil / trunc
Rounding primitives
mean / median / stdev
Descriptive statistics
Estimated Time
30 Minutes
Comprehensive deep dive
Difficulty Level
Intermediate
Builds on Functions & Data Types
Knowledge Check
15 Questions
+35 XP Potential
01 / Foundations

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.

Direct comparison antipattern
print(0.1 + 0.2 == 0.3) # False!
Tolerance-based comparison
print(math.isclose(0.1 + 0.2, 0.3)) # True
Think of it like this:

The statistics module is an automated accountant — finding averages, medians, and variance across numbers in a single call, without manually tallying anything by hand.

Full Contract in Action

Safe Floating-Point Comparisons with math.isclose

Run the snippet below to see why direct float equality fails and how math.isclose() fixes it:

float_precision_intro.py — Press 'Run Code' to execute in your browser
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 & Statistics Glossary: Core Concepts
math.isclose()Precision

Safely compares two floats within a relative or absolute tolerance margin.

decimal.DecimalExactness

Fixed-point base-10 arithmetic for audit-grade financial calculations.

math.floor / ceil / truncRounding

Three distinct rounding directions: toward -inf, toward +inf, and toward zero.

statistics.median()Robustness

The middle value of a dataset — resilient to outliers, unlike the mean.

02 / Precision & Statistics Tracer

Trace How Each Technique Works

Click through each technique to see its exact behavior:

math.isclose() — Safe Float Comparison
a = 0.1 + 0.2 b = 0.3 a == b # False! (0.30000000000000004) math.isclose(a, b) # True

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.

03 / Math & Statistics Reference

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.

04 / Hands-on Examples

Worked Hands-on Walkthroughs

Progress step-by-step from safe float comparisons, through exact financial arithmetic, to analyzing real latency data:

Walkthrough 01 · FoundationLevel 1 · Foundation

Safe Floating-Point Comparisons with math.isclose

math.isclose()
Problem Scenario

math.isclose safely evaluates floating-point equality without suffering from binary fraction discrepancies.

Executable Solution
Safe Floating-Point Comparisons with math.isclose
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))
Step-by-Step Explanation

math.isclose safely evaluates floating-point equality without suffering from binary fraction discrepancies.

Walkthrough 02 · Building UpLevel 2 · Applied

Financial Ledger Calculations with decimal.Decimal

decimal.Decimal
Problem Scenario

Decimal provides deterministic, audit-grade arithmetic with customizable rounding modes.

Executable Solution
Financial Ledger Calculations with decimal.Decimal
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)
Step-by-Step Explanation

Decimal provides deterministic, audit-grade arithmetic with customizable rounding modes.

Walkthrough 03 · MasteryLevel 3 · Architecture

Analyzing System Latencies with the statistics Module

statistics
Problem Scenario

Because of the single 120ms spike, the mean is skewed to 57ms, while the median (50.5ms) represents typical user experience.

Executable Solution
Analyzing System Latencies with the statistics Module
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]}")
Step-by-Step Explanation

Because of the single 120ms spike, the mean is skewed to 57ms, while the median (50.5ms) represents typical user experience.

05 / Traps to Avoid

Common Traps & How to Avoid Them

Study the mistakes and clean fixes below before relying on numerical calculations in production:

!Trap 1: Syntax or Name Typos in Math & Statistical Analysis
Common Trap
The Bug (Avoid)Buggy Code
# Mistyped variable or missing closing parenthesis result = math___statistical_analysis_val
What Happens:
NameError: name is not defined
The Clean FixCorrected Code
# Declare and verify variables before execution val = 10 print("Defined correctly:", val)
Recommended Practice:
Never compare floats with ==, and never construct Decimal from a raw float — always pass a string.
Why It Happens

Beginners frequently encounter typos or forgotten definitions before using an identifier.

!Trap 2: Unintended State Mutation or Scope Leakage
Subtle Trap
The Bug (Avoid)Buggy Code
# Modifying shared state or unexpected variable shadowing def update_state(data=[]): data.append(1) return data
What Happens:
Default mutable argument accumulates values across separate function calls.
The Clean FixCorrected Code
def update_state(data=None): if data is None: data = [] data.append(1) return data
Recommended Practice:
Never compare floats with ==, and never construct Decimal from a raw float — always pass a string.
Why It Happens

Default arguments in Python are evaluated once at function definition time, not at invocation time.

!Trap 3: Resource Leaks & High-Scale Performance Regressions
Architecture Trap
The Bug (Avoid)Buggy Code
# Opening resources in a tight loop without closing or bounding memory files = [open(f"log_{i}.txt", "w") for i in range(5000)]
What Happens:
OSError: [Errno 24] Too many open files (file descriptor exhaustion)
The Clean FixCorrected Code
for i in range(5): with open(f"log_{i}.txt", "w") as f: f.write("Safe")
Recommended Practice:
Never compare floats with ==, and never construct Decimal from a raw float — always pass a string.
Why It Happens

Failing to release system resources leads to process termination under heavy production workloads.

06 / Real-World Systems

Real-World Systems in Action

See how scripts, backend services, and SRE monitoring pipelines all rely on precise numerical computation at scale:

Developer ProductivityFoundation Script

Local Developer Automation Tool

SYSTEM #1
Organization Context

Individual developers and IT administrators automate everyday repetitive workflows.

Why This Pattern Works Here

A clean standalone script providing fast, local automation with zero dependencies.

Production Code Wrapper
Local Developer Automation Tool
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))
Cloud MicroservicesScaled Service · Applied

Backend API Service Integration

SYSTEM #2
Organization Context

SaaS platforms run backend microservices processing requests concurrently.

Why This Pattern Works Here

A modular service handler integrating validation and structured responses.

Production Code Wrapper
Backend API Service Integration
# Service integration layer
def handle_request(payload: dict) -> dict:
    return {"status": "success", "processed": True}
Distributed SystemsEnterprise · Architecture

High-Throughput Cloud Architecture

SYSTEM #3
Organization Context

Site reliability engineering (SRE) monitoring agents compute p50, p90, and p99 service latencies to trigger automated auto-scaling.

Why This Pattern Works Here

Site reliability engineering (SRE) monitoring agents compute p50, p90, and p99 service latencies to trigger automated auto-scaling.

Production Code Wrapper
High-Throughput Cloud Architecture
# High-resilience production pattern
import time

def process_stream(events: list) -> int:
    processed = 0
    for event in events:
        if event:
            processed += 1
    return processed
Key Takeaways

Key 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.
Study Guide & References

Frequently Asked Questions & Reference Hub

FAQ & References
Growth Mindset: Let the Question Choose the Tool

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.

Related Built-in References Right Here
PyLabs Library Docs
Official External Guides:Python Docs — statistics Module
Ready for Action

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.

Hands-on Code Challenge

Compute the mean and median of a scores dataset and format the output exactly.

+40 XP Reward

Earn experience points toward your developer rank as soon as you pass.

~3 Minutes to Complete

Bite-sized knowledge check with instant explanations for every question.

Worked example

Compute the average of test scores with statistics.mean.

Example
import statistics
print(int(statistics.mean([10, 20, 30])))

How it works, step by step

  1. statistics.mean computes the arithmetic average.

Your notes

Sign in to keep private notes alongside this lesson.

Sign in to take notes

Math & Statistical Computations practice

Sign-in required

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

Locked

You must be signed in to take this quiz. Sign in to test your understanding, track your answers, and earn XP.

Lesson incomplete

Not completed

Create an ID or sign in to save lesson completion across devices.

Create ID to save
Module lesson progress0/6 complete
Module cheat sheet