Probability & Statistics Fundamentals
A Complete 10-Chapter Maths for Programmers Course
Table of Contents
- Why Probability & Statistics Matter for Programmers
- Sample Spaces, Events & Basic Probability Rules
- Conditional Probability & Independence
- Bayes' Theorem
- Random Variables & Expected Value
- The Binomial Distribution
- The Poisson Distribution
- The Normal Distribution & the Central Limit Theorem
- Descriptive Statistics: Mean, Median, Variance & Standard Deviation
- Capstone — Probability & Statistics in Practice
Why Probability & Statistics Matter for Programmers
Probability & Statistics Fundamentals
Chapter 1 · Why Probability & Statistics Matter for Programmers
Every system you build eventually runs into something it can't fully control — a request that might fail, a user who might click, a server that might go down at an inconvenient hour. Probability and statistics are the two branches of math built specifically for reasoning carefully about exactly that kind of uncertainty, rather than guessing or hoping it averages out.
Probability vs. Statistics — Two Directions of Reasoning
These two names get used almost interchangeably in casual conversation, but they answer genuinely opposite questions.
| Probability | Statistics | |
|---|---|---|
| Direction | Model → predicted outcomes | Observed data → inferred model |
| Starting point | You already know the rules (a fair coin, a known defect rate) | You only have data, and need to work out what's actually going on |
| Example question | "Given a fair die, what's the chance of rolling a 6?" | "Given 10,000 actual page loads, what's the real average response time?" |
| Core tools | Probability rules, distributions (Ch.2–8 of this course) | Descriptive statistics (Ch.9), and inferential methods — this subject's own separate future course |
Both matter, and in practice they're used together constantly — you build a probability model of how something should behave, then use statistics to check whether real, observed data actually matches it. This particular course focuses on the probability side and the basic descriptive tools for summarizing data; the reasoning-from-data-back-to-conclusions side (confidence intervals, hypothesis testing, A/B testing, regression) is deliberately this subject's own separate next course.
Five Concrete Connections to Code Already On This Site
Every topic in this course maps onto something already relevant to real engineering work, whether or not the underlying math was ever named:
| Probability/statistics topic | Where it actually shows up |
|---|---|
| Probability rules & conditional probability (Ch.2–3) | Retry logic and compounding failure rates, cache-hit probability, error-rate budgets |
| Bayes' Theorem (Ch.4) | Spam filters and fraud-detection systems that combine several weak, individually unreliable signals into one updated probability |
| Random variables & expected value (Ch.5) | Estimating expected cost, expected load, or expected risk before a decision is made — not just the single most likely outcome |
| Distributions — binomial, Poisson, normal (Ch.6–8) | Modelling conversion rates (binomial), server incident/arrival rates (Poisson — directly relevant to Technical Support's own perfdiag1/incident1 material), and noisy measurement error (normal) |
| Descriptive statistics (Ch.9) | Every monitoring dashboard's own averages, and the well-known trap (already covered from the other direction in perfdiag1's own material) that an average can quietly hide a real spike |
What This Course Won't Cover
A substantial, genuinely related set of topics is deliberately left for this subject's own next course, Statistical Inference & Applied Statistics, rather than folded in here:
- Sampling & confidence intervals — how to reason honestly about uncertainty in an estimate drawn from a sample rather than an entire population
- Hypothesis testing & A/B testing — the formal machinery for deciding whether an observed difference is real or just noise
- Correlation, regression & Bayesian updating — inferring relationships between variables from real data, and formally updating a belief as new evidence arrives
Where This Course Is Headed
| Chapter | Topic |
|---|---|
| 2 | Sample Spaces, Events & Basic Probability Rules |
| 3 | Conditional Probability & Independence |
| 4 | Bayes' Theorem |
| 5 | Random Variables & Expected Value |
| 6 | The Binomial Distribution |
| 7 | The Poisson Distribution |
| 8 | The Normal Distribution & the Central Limit Theorem |
| 9 | Descriptive Statistics — Mean, Median, Variance & Standard Deviation |
| 10 | Capstone — Probability & Statistics in Practice |
Hands-On Exercises
Classify each of the following as fundamentally a probability question (model → predicted outcome) or a statistics question (data → inferred conclusion), and briefly justify each answer: (a) given a fair six-sided die, what's the chance of rolling a 6? (b) given 1,000 recorded server response times, what's their average? (c) given a known 2% manufacturing defect rate, how many defective units are expected in a batch of 500? (d) given last month's actual incident counts, estimate the true underlying incident rate.
📄 View solutionA colleague claims "probability and statistics are only really relevant if you're doing data science or machine learning." Using this chapter's own five connections, explain at least two places probability/statistics reasoning shows up in code that has nothing to do with ML.
📄 View solutionFor each of the following real system-design scenarios, name which topic from this chapter's own five-connections table it most directly maps to, and explain the connection in one or two sentences: (a) a retry mechanism where each attempt independently succeeds 90% of the time, and you want to know the chance all three attempts fail; (b) a fraud-detection system combining an unusual login location, an unusual purchase amount, and a new device into one overall risk score; (c) a dashboard graph showing "average response time" over the last hour.
📄 View solutionChapter 1 Quick Reference
- Probability reasons from a known model forward to predicted outcomes; statistics reasons from observed data backward to an inferred model
- Five direct connections: probability rules → retries/error budgets, Bayes' Theorem → spam/fraud filters, expected value → risk/cost estimation, distributions → conversion rates & incident rates & measurement noise, descriptive stats → dashboard averages
- Deliberately out of scope here: sampling, confidence intervals, hypothesis testing, A/B testing, regression, and Bayesian updating — all reserved for this subject's own next course, Statistical Inference & Applied Statistics
- This course builds the probability vocabulary and distributions every inferential technique in that next course is built on top of
- Next chapter: Sample spaces, events, and the basic rules of probability
Sample Spaces, Events & Basic Probability Rules
Probability & Statistics Fundamentals
Chapter 2 · Sample Spaces, Events & Basic Probability Rules
Every probability question starts by pinning down two things precisely: every outcome that could possibly happen, and the specific outcomes you actually care about. Get those two definitions right, and most basic probability calculations turn into simple counting — genuinely just set operations wearing a different name.
Sample Space & Events
The sample space (usually written S) is the set of every possible outcome of an experiment. An event is any subset of that sample space — the specific outcomes that count as a "success" for whatever question is being asked.
S = {1, 2, 3, 4, 5, 6}Event A ("rolling an even number") =
{2, 4, 6}Event B ("rolling a number greater than 4") =
{5, 6}
A ∩ B; "A or B" is the union A ∪ B; "not A" is the complement. Every probability rule in this chapter is really a Discrete Mathematics Fundamentals Chapter 4 set operation, counted and divided.
Computing Probability for Equally Likely Outcomes
When every outcome in the sample space is equally likely (a fair die, a fair coin), probability is a straightforward ratio:
P(event) = |event| / |sample space|
For event A above: P(A) = |{2,4,6}| / |{1,...,6}| = 3/6 = 0.5. For event B: P(B) = |{5,6}| / 6 = 2/6 = 1/3.
The Probability Axioms
Every valid probability assignment must satisfy three basic rules, regardless of how the probabilities were derived:
| Axiom | Meaning |
|---|---|
| Non-negativity | 0 ≤ P(event) ≤ 1 for any event |
| Certainty | P(S) = 1 — something in the sample space is guaranteed to happen |
| Impossibility | P(∅) = 0 — the empty event (no outcomes) never happens |
The Complement Rule
The complement of an event, written Aᶜ ("not A"), is every outcome not in A. Since A and Aᶜ together always cover the whole sample space exactly once:
P(Aᶜ) = 1 − P(A)
The probability of not rolling a 6: P(not 6) = 1 − 1/6 = 5/6. Often faster than counting the complement's outcomes directly, especially when "not A" covers far more cases than "A" does.
The Union (Addition) Rule
For "A or B," the naive instinct is to add P(A) + P(B) — but that double-counts any outcome that belongs to both events. The correct rule subtracts the overlap back out:
P(A ∪ B) = P(A) + P(B) − P(A ∩ B)
Continuing the dice example: A ∩ B = {6} (even and greater than 4), so P(A ∩ B) = 1/6.
| Quantity | Value |
|---|---|
| P(A) + P(B) | 0.5 + 0.333 = 0.833 (5/6) — wrong, double-counts 6 |
| P(A) + P(B) − P(A ∩ B) | 0.5 + 0.333 − 0.167 = 0.667 (2/3) — correct |
| Direct check: |A ∪ B| / |S| | {2,4,5,6} → 4/6 = 2/3 ✓ matches |
P(A) + P(B) counts outcome 6 twice — once as part of "even," once as part of "greater than 4" — inflating the true answer. Whenever two events can genuinely overlap, skipping the − P(A ∩ B) term silently overstates the real probability.
Mutually Exclusive Events — When the Simple Sum Is Correct
If two events can never both happen at once (A ∩ B = ∅), they're called mutually exclusive — and the subtraction term simply vanishes, since P(∅) = 0:
P(A ∪ B) = P(A) + P(B) — only valid when A ∩ B = ∅
Rolling a 1 (C = {1}) and rolling a 6 (D = {6}) can never both happen on the same roll: P(C ∪ D) = 1/6 + 1/6 = 1/3 — directly correct here, with no overlap to subtract.
Sample Spaces & Events in Code
Hands-On Exercises
A standard 52-card deck. Event A = "drawing a heart" (13 cards). Event B = "drawing a face card" (Jack, Queen, or King — 12 cards total across all suits). Compute P(A), P(B), and P(A ∩ B) (hearts that are also face cards), then use the union rule to find P(A ∪ B). Confirm your answer by directly counting how many of the 52 cards satisfy "heart or face card."
Out of 500 requests handled by a service last week, 15 returned an error. Using the complement rule, compute the probability that a randomly selected request from that week did not return an error.
📄 View solutionRolling a single die: event E = "rolling an odd number" ({1,3,5}), event F = "rolling a number less than 4" ({1,2,3}). Compute P(E), P(F), and P(E ∩ F), then use the union rule to find P(E ∪ F). Separately, compute the naive (incorrect) sum P(E) + P(F) and explain specifically which outcome(s) it double-counts.
Chapter 2 Quick Reference
- Sample space = every possible outcome; event = a subset of the sample space
- Equally-likely-outcomes formula:
P(event) = |event| / |sample space|— only valid when every outcome is equally likely - Axioms:
0 ≤ P(event) ≤ 1,P(S) = 1,P(∅) = 0 - Complement rule:
P(Aᶜ) = 1 − P(A) - Union rule:
P(A ∪ B) = P(A) + P(B) − P(A ∩ B)— the subtraction fixes double-counting the overlap - Mutually exclusive events (
A ∩ B = ∅) simplify toP(A ∪ B) = P(A) + P(B), with nothing to subtract - Next chapter: Conditional probability and independence
Conditional Probability & Independence
Probability & Statistics Fundamentals
Chapter 3 · Conditional Probability & Independence
Chapter 2's rules all assumed no extra information. Real questions are rarely that clean — "what's the chance this request fails, given that the last three also failed?" This chapter is about updating a probability once new information narrows down what's actually possible.
Conditional Probability — Narrowing the Sample Space
Conditional probability, written P(A|B) ("the probability of A, given B"), asks: once we know B has happened, what fraction of that narrowed-down world does A still cover?
P(A|B) = P(A ∩ B) / P(B)
Reusing Chapter 2's dice example: S = {1,...,6}, A = "even" = {2,4,6}, B = "greater than 4" = {5,6}, A ∩ B = {6}.
| Quantity | Calculation | Result |
|---|---|---|
| P(A|B) | (1/6) / (1/3) | 1/2 — given the roll is 5 or 6, half the time it's also even |
| P(B|A) | (1/6) / (1/2) | 1/3 — given the roll is even, only 1 in 3 times is it also >4 |
Independence
Two events are independent if knowing one happened tells you nothing new about the other: P(A|B) = P(A). Rearranging the conditional probability formula gives an equivalent, more practical test:
A and B are independent ⟺ P(A ∩ B) = P(A) × P(B)
P(A) × P(B) = 0.5 × (1/3) = 1/6, which exactly equals P(A ∩ B) = 1/6. "Even" and "greater than 4" are, on a fair die, actually independent — a fact that isn't obvious just by looking at the two events, and only confirmed by checking the numbers directly. Never assume independence from intuition alone; always check.
For contrast, reusing Chapter 2's own exercise events E = "odd" = {1,3,5} and F = "less than 4" = {1,2,3}: P(E) × P(F) = 0.5 × 0.5 = 0.25, but P(E ∩ F) = P({1,3}) = 1/3 ≈ 0.333. Since 0.25 ≠ 0.333, E and F are dependent — knowing a roll is odd genuinely does change the probability it's also less than 4.
The Multiplication Rule for Independent Events, in Practice
When events genuinely are independent, the multiplication rule becomes a fast, direct tool — and it generalizes cleanly to more than two events, which is exactly what reliability calculations need.
| Quantity | Calculation | Result |
|---|---|---|
| P(all 3 fail) | 0.1 × 0.1 × 0.1 | 0.001 (0.1%) |
| P(at least one succeeds) | 1 − 0.001 (complement rule, Ch.2) | 0.999 (99.9%) |
This is the exact combination of two rules from this course so far: the multiplication rule for independent events, and Chapter 2's own complement rule, chained together to answer a genuinely practical reliability question.
The General Multiplication Rule — A Bayes' Theorem Forward Reference
Rearranging the conditional probability formula, without assuming independence, gives the fully general version:
P(A ∩ B) = P(A|B) × P(B) = P(B|A) × P(A)
That last equality — two different ways of writing the exact same joint probability — is the entire foundation Chapter 4's Bayes' Theorem is built from. It's what makes it possible to solve for P(B|A) when only P(A|B) is actually known, which turns out to be an extremely common real situation.
Conditional Probability & Independence in Code
Hands-On Exercises
Rolling a single die: event G = "rolling a number ≤ 3" ({1,2,3}), event H = "rolling an even number" ({2,4,6}). Compute P(G|H) and P(H|G), and determine whether G and H are independent by applying this chapter's own multiplication-rule test.
An operation is retried up to 4 times, each attempt independently succeeding 80% of the time. Compute the probability all 4 attempts fail, and the probability at least one succeeds.
📄 View solutionIn a product analytics dataset: P(user is on mobile) = 0.6, P(user completes checkout) = 0.1, P(user is on mobile AND completes checkout) = 0.03. Compute P(checkout | mobile), compare it to the overall P(checkout) to say whether mobile users are more or less likely than average to complete checkout, and determine whether "on mobile" and "completes checkout" are independent events.
Chapter 3 Quick Reference
- Conditional probability:
P(A|B) = P(A ∩ B) / P(B)— the probability of A, restricted to the world where B already happened - P(A|B) ≠ P(B|A) in general — confusing the two is a classic real mistake
- Independence:
P(A|B) = P(A), equivalentlyP(A ∩ B) = P(A) × P(B)— always check the numbers, never assume from intuition - The independent-events multiplication rule generalizes to any number of events — e.g.,
P(all n fail) = p^nfor n independent attempts each with failure probability p - General multiplication rule:
P(A ∩ B) = P(A|B)P(B) = P(B|A)P(A)— the direct foundation of Chapter 4's Bayes' Theorem - Next chapter: Bayes' Theorem
Bayes' Theorem
Probability & Statistics Fundamentals
Chapter 4 · Bayes' Theorem
Chapter 3 ended with a promise: a way to solve for P(B|A) when only P(A|B) is actually known. That tool is Bayes' Theorem — and it delivers one of the most consistently surprising, genuinely useful results in this entire course.
Deriving Bayes' Theorem
Chapter 3's general multiplication rule gave two equal expressions for the same joint probability:
P(A ∩ B) = P(A|B) × P(B) = P(B|A) × P(A)
Dropping the middle term and dividing both sides by P(A) isolates P(B|A) directly:
P(B|A) = [P(A|B) × P(B)] / P(A)
Written in the notation it's usually taught with — H for hypothesis, E for evidence:
P(H|E) = [P(E|H) × P(H)] / P(E)
Each term has a name worth knowing: P(H) is the prior (what you believed before seeing the evidence), P(E|H) is the likelihood, P(E) is the evidence's overall probability, and P(H|E) is the posterior — the updated belief after accounting for the evidence.
The Law of Total Probability — Filling in the Denominator
P(E) is rarely given directly — it needs to be built from the two ways evidence can occur: when the hypothesis is true, and when it's false.
P(E) = P(E|H) × P(H) + P(E|not H) × P(not H)
The Classic Example: A Diagnostic Test
A test for a rare disease is genuinely quite accurate:
| Quantity | Value |
|---|---|
| P(D) — disease prevalence | 1% (a rare disease) |
| P(+|D) — sensitivity | 99% — correctly flags 99% of people who have it |
| P(+|not D) — false positive rate | 5% — incorrectly flags 5% of healthy people |
Question: given a positive result, what's the actual probability of having the disease?
| Step | Calculation | Result |
|---|---|---|
| P(+), total probability | 0.99×0.01 + 0.05×0.99 | 0.0594 |
| P(D|+), Bayes' Theorem | (0.99×0.01) / 0.0594 | 0.1667 (≈16.7%) |
A Second Worked Example: A Spam Filter
Reusing this course's own forward reference from Chapter 1 — a spam filter reasoning about a single word:
| Quantity | Value |
|---|---|
| P(spam) — prior | 40% of all email is spam |
| P("free"|spam) | 30% of spam emails contain the word "free" |
| P("free"|not spam) | 5% of legitimate emails contain "free" |
| Step | Calculation | Result |
|---|---|---|
| P("free"), total probability | 0.30×0.40 + 0.05×0.60 | 0.15 |
| P(spam|"free"), Bayes' Theorem | (0.30×0.40) / 0.15 | 0.80 (80%) |
Seeing "free" in an email raises the belief it's spam from a 40% prior all the way to an 80% posterior — a real, quantified update, exactly the mechanism named in Chapter 1's own connections table.
Why This Matters for Real Alerting Systems
secsupport1, incident1) deal with directly from the response-process side; this chapter explains exactly why it happens numerically.
Bayes' Theorem in Code
Hands-On Exercises
A fraud-detection system flags 95% of genuinely fraudulent transactions (P(flagged|fraud) = 0.95) and incorrectly flags 2% of legitimate transactions (P(flagged|not fraud) = 0.02). Only 0.1% of all transactions are actually fraudulent (P(fraud) = 0.001). Using Bayes' Theorem, compute P(fraud|flagged) — the actual probability a flagged transaction is really fraud.
A different spam filter: 30% of email is spam (P(spam) = 0.30), 25% of spam emails contain the word "winner" (P("winner"|spam) = 0.25), and 1% of legitimate emails contain "winner" (P("winner"|not spam) = 0.01). Compute P(spam|"winner") using this chapter's own Bayes' Theorem method.
An intrusion-detection system has a 99% true-positive rate (P(alert|malicious) = 0.99) and a 1% false-positive rate (P(alert|not malicious) = 0.01). Only 1 in 10,000 connections on the network is actually malicious. Compute P(malicious|alert), and explain — using this chapter's own base-rate-neglect finding — what this result means for whether the system is genuinely "good enough" to alert a human on every trigger.
Chapter 4 Quick Reference
- Bayes' Theorem:
P(H|E) = [P(E|H) × P(H)] / P(E)— derived directly from Chapter 3's general multiplication rule - Prior P(H), likelihood P(E|H), posterior P(H|E) — the belief before and after accounting for evidence
- Law of total probability:
P(E) = P(E|H)P(H) + P(E|not H)P(not H)— needed whenever P(E) isn't given directly - A highly accurate test can still produce a low posterior when the underlying condition (the prior) is rare — base-rate neglect
- The same math explains why real intrusion/anomaly-detection alerts are often mostly false positives, and why alert fatigue is a real, quantifiable consequence, not just an inconvenience
- Next chapter: Random variables and expected value
Random Variables & Expected Value
Probability & Statistics Fundamentals
Chapter 5 · Random Variables & Expected Value
Every chapter so far has asked about the probability of a specific event. This chapter asks a slightly different question: given a whole range of numeric outcomes, each with its own probability, what's a single number that fairly summarizes the whole situation? That number is the expected value, and it's the mathematical foundation of essentially every risk, cost, and budgeting calculation built on top of uncertainty.
Random Variables & Probability Distributions
A random variable (conventionally written as a capital letter, like X) assigns a number to every outcome in a sample space. Its probability distribution (or probability mass function, for a discrete variable) lists every possible value it can take, together with the probability of each.
X = the value shown. Every value 1 through 6 has probability 1/6 — a genuinely uniform distribution.
Expected Value
The expected value E[X] is the probability-weighted average of every possible outcome:
E[X] = Σ x · P(X = x) — sum over every possible value x
For the die: E[X] = (1+2+3+4+5+6)/6 = 21/6 = 3.5.
Worked Example: Expected Weekly Incident Cost
A service's weekly incident cost, X, has this distribution:
| Outcome (cost) | Probability | Scenario |
|---|---|---|
| $0 | 0.70 | No incident |
| $500 | 0.20 | Minor incident |
| $5,000 | 0.08 | Major incident |
| $50,000 | 0.02 | Catastrophic incident |
(Probabilities sum to exactly 1.0, as any valid distribution must — Chapter 2's own certainty axiom.)
| Term | Calculation |
|---|---|
| 0 × 0.70 | 0 |
| 500 × 0.20 | 100 |
| 5,000 × 0.08 | 400 |
| 50,000 × 0.02 | 1,000 |
E[X] = 0 + 100 + 400 + 1,000 = $1,500 — the expected weekly incident cost, useful directly for budgeting a reserve fund or setting an insurance premium, exactly the reasoning behind Technical Support's own backup1/incident1 material approached from a numeric angle.
Variance & Standard Deviation of a Random Variable
Expected value alone hides something important: how spread out the possible outcomes actually are. Variance measures that spread directly, for a known distribution — a genuinely different calculation from Chapter 9's own variance, which is computed from real, already-collected sample data rather than a theoretical distribution.
Var(X) = E[X²] − (E[X])², and SD(X) = √Var(X)
For the incident-cost example: E[X²] = 0²(0.70) + 500²(0.20) + 5,000²(0.08) + 50,000²(0.02) = 0 + 50,000 + 2,000,000 + 50,000,000 = 52,050,000.
| Quantity | Value |
|---|---|
| Var(X) | 52,050,000 − 1,500² = 49,800,000 |
| SD(X) | √49,800,000 ≈ $7,057 |
Random Variables & Expected Value in Code
Hands-On Exercises
A company's monthly new-signups count, X, has the distribution: P(X=100) = 0.5, P(X=200) = 0.3, P(X=500) = 0.2. Confirm the probabilities sum to 1, then compute E[X].
A feature-flag rollout has three possible cost outcomes: no issues (probability 0.85, cost $0), a minor rollback (probability 0.12, cost $2,000), a major outage (probability 0.03, cost $80,000). Compute E[X], Var(X), and SD(X). Given how large the standard deviation is relative to the mean, what does this chapter's own finding suggest about relying on the expected value alone to decide whether the rollout is "safe enough"?
Using this chapter's own incident-cost example (E[X] = $1,500 per week), explain in your own words why "the expected cost over the next 1,000 weeks is $1,500,000" is a reasonable statement to make, even though no single week is ever likely to cost exactly $1,500. Ground your answer in this chapter's own "long-run average, not a single prediction" distinction.
Chapter 5 Quick Reference
- Random variable: assigns a number to every outcome; its distribution lists every value with its probability, summing to exactly 1
- Expected value:
E[X] = Σ x · P(X=x)— a probability-weighted average, and a long-run average, not a prediction of any single outcome - Variance of a random variable:
Var(X) = E[X²] − (E[X])²; standard deviation is its square root — distinct from Chapter 9's own sample-based variance, computed from real collected data rather than a known distribution - A large standard deviation relative to the mean signals a risky, skewed distribution — expected value alone can badly understate real risk
- Next chapter: The binomial distribution
The Binomial Distribution
Probability & Statistics Fundamentals
Chapter 6 · The Binomial Distribution
Chapter 5 covered random variables in general — any list of outcomes and probabilities was fair game. This chapter is about the single most common specific shape that list takes in real engineering work: counting how many times something succeeds out of a fixed number of independent attempts, each with the same fixed probability.
When the Binomial Distribution Applies
The binomial distribution requires four conditions, all of which are worth checking explicitly before using it:
| Condition | Meaning |
|---|---|
| Fixed number of trials | n is decided in advance, not itself random |
| Two outcomes per trial | Each trial is a "success" or "failure" — nothing in between |
| Fixed success probability | Every trial has the exact same probability p of success |
| Independent trials | One trial's outcome doesn't affect any other's — Chapter 3's own independence, required here explicitly |
The Binomial Formula
X = the number of successes in n trials. The probability of getting exactly k successes is:
P(X = k) = C(n, k) × pᵏ × (1−p)ⁿ⁻ᵏ
C(n, k) is "n choose k" — the number of different ways to pick which k of the n trials were the successes (the same combinations formula from Discrete Mathematics Fundamentals Chapter 9, for anyone who's taken that course; here it's just n! / (k! (n−k)!)). The rest of the formula is one specific sequence's own probability — pᵏ for the k successes, (1−p)ⁿ⁻ᵏ for the remaining failures — multiplied by how many different sequences produce that same count.
Worked Example: Flipping a Coin
Flip a fair coin n = 4 times. X = number of heads. What's P(X = 2)?
| Term | Value |
|---|---|
| C(4, 2) | 6 |
| p² = 0.5² | 0.25 |
| (1−p)² = 0.5² | 0.25 |
| P(X=2) = 6 × 0.25 × 0.25 | 0.375 |
Mean & Variance — A Shortcut Built on Chapter 5
Computing E[X] and Var(X) the long way, using Chapter 5's own formulas across every possible value of k, works — but the binomial distribution has direct shortcuts that skip all of it:
E[X] = np Var(X) = np(1−p)
For the coin-flip example: E[X] = 4 × 0.5 = 2 heads on average, Var(X) = 4 × 0.5 × 0.5 = 1.
A Practical Example: A/B Test Conversions
A new checkout flow has a 20% conversion rate (p = 0.2). Out of the next n = 10 users, what's the probability exactly 3 convert?
| Term | Value |
|---|---|
| C(10, 3) | 120 |
| p³ = 0.2³ | 0.008 |
| (1−p)⁷ = 0.8⁷ | 0.2097 |
| P(X=3) = 120 × 0.008 × 0.2097 | ≈ 0.2013 (20.1%) |
E[X] = 10 × 0.2 = 2 expected conversions, Var(X) = 10 × 0.2 × 0.8 = 1.6, SD(X) ≈ 1.26. This exact framing — a fixed conversion rate applied across a fixed number of users — is precisely the model behind Probability & Statistics Fundamentals' own sibling course, Statistical Inference & Applied Statistics, and its A/B testing material.
Revisiting Chapter 1's Defect-Rate Example
Chapter 1's own opening exercise asked: given a known 2% defect rate, how many defects are expected in a batch of 500? That's exactly E[X] = np = 500 × 0.02 = 10 — the binomial mean, finally formalized. The full distribution can answer sharper questions too:
P(X = 0) = C(500, 0) × 0.02⁰ × 0.98⁵⁰⁰ ≈ 0.000041 — about a 0.004% chance. Even though 10 defects is only "expected," an entirely defect-free batch of this size, at this defect rate, would be a genuinely remarkable outcome, not a plausible one.
The Binomial Distribution in Code
Hands-On Exercises
Flip a fair coin 5 times. Using this chapter's own binomial formula, compute P(exactly 3 heads), showing the C(n,k), pᵏ, and (1−p)ⁿ⁻ᵏ terms separately before combining them.
A new signup flow converts 15% of visitors (p = 0.15). Out of the next 8 visitors, compute P(exactly 2 convert), and separately compute E[X] and Var(X) using this chapter's own mean/variance shortcuts.
A batch of 20 units has a 5% defect rate. Compute P(exactly 1 defective unit), and separately compute E[X] using the mean shortcut. Then name which of this chapter's own four required conditions would be violated if the real cause of defects were a single faulty machine setting affecting every unit in the batch identically, and briefly explain the practical consequence.
Chapter 6 Quick Reference
- Requires: a fixed number of trials
n, two outcomes per trial, a fixed success probabilityp, and independent trials - PMF:
P(X=k) = C(n,k) × pᵏ × (1−p)ⁿ⁻ᵏ— combinations × one sequence's own probability - Mean/variance shortcuts:
E[X] = np,Var(X) = np(1−p)— skip Chapter 5's full sum-over-every-value calculation - Models conversion rates, defect rates, and any "how many successes out of n fixed independent attempts" question
- Always verify independence and a genuinely fixed probability before trusting the model — correlated failures break both assumptions
- Next chapter: The Poisson distribution
The Poisson Distribution
Probability & Statistics Fundamentals
Chapter 7 · The Poisson Distribution
Chapter 6's binomial distribution needed a fixed, countable number of trials — flip the coin exactly 4 times, check exactly 500 units. Plenty of real questions don't have a natural "number of trials" at all: how many incidents hit a server in a week? How many requests arrive at an endpoint in a second? There's no fixed n to point to — just a rate. The Poisson distribution is built specifically for exactly that shape of question.
What the Poisson Distribution Models
The Poisson distribution counts how many times a rare, independent event happens within a fixed interval (of time, space, or anything else continuous), given only the average rate at which it happens — a single parameter, conventionally called λ (lambda).
P(X = k) = (λᵏ × e⁻λ) / k!
e here is Euler's number (≈2.71828), the same constant used throughout continuous math; k! is a factorial, exactly Discrete Mathematics Fundamentals Chapter 9's own territory for anyone who's taken that course. λ is both the distribution's only parameter and, conveniently, its mean.
Mean, Variance — and a Distinctive Property
E[X] = λ Var(X) = λ
np(1−p), is always strictly less than its mean np, since (1−p) < 1. The Poisson distribution has no such gap — its variance is always exactly equal to its mean. This is actually a useful real-world diagnostic: if a dataset that's supposedly Poisson-distributed shows a variance noticeably larger than its mean ("overdispersion"), that's a signal the independence or constant-rate assumption is probably broken — real incidents often cluster (one root cause triggers several), which inflates variance beyond what pure Poisson randomness would predict.
Worked Example: Weekly Server Incidents
A service experiences an average of λ = 3 incidents per week. What's the probability of exactly 5 incidents in a given week?
| Term | Value |
|---|---|
| λ⁵ = 3⁵ | 243 |
| e⁻³ | ≈ 0.0498 |
| 5! | 120 |
| P(X=5) = (243 × 0.0498) / 120 | ≈ 0.1008 (10.1%) |
For contrast, the probability of a completely quiet, incident-free week: P(X=0) = (3⁰ × e⁻³) / 0! = e⁻³ ≈ 0.0498 — about a 5% chance, despite the average being 3 incidents. This is directly Technical Support's perfdiag1/incident1 territory, now with a precise number attached instead of just "incidents happen sometimes."
A Second Example: Request Arrival Rate
An API endpoint receives an average of λ = 2 requests per second. What's the probability of exactly 4 requests arriving in a given second?
| Term | Value |
|---|---|
| λ⁴ = 2⁴ | 16 |
| e⁻² | ≈ 0.1353 |
| 4! | 24 |
| P(X=4) = (16 × 0.1353) / 24 | ≈ 0.0902 (9.0%) |
This is the exact reasoning behind capacity planning: knowing the full distribution of "requests per second," not just the average, is what lets a team provision for the realistic worst case rather than just the mean.
The Poisson Distribution as a Limit of the Binomial
The Poisson distribution isn't an unrelated new idea — it's what the binomial distribution turns into when n gets very large and p gets very small, while their product np stays fixed at λ. This makes intuitive sense: "requests per second" has effectively infinite tiny sub-instants where a request could arrive (huge n), each individually very unlikely (tiny p), but the overall rate λ = np stays meaningful.
| Model | P(X=0), n=10,000, p=0.0002 (λ=2) |
|---|---|
| Exact binomial | 0.135308... |
| Poisson approximation (λ=2) | 0.135335... |
The two agree to four decimal places — confirming the Poisson distribution as a genuinely accurate, and far simpler, stand-in whenever n is huge and p is tiny.
The Poisson Distribution in Code
Hands-On Exercises
A different service averages λ = 2 incidents per week. Using this chapter's own Poisson formula, compute P(exactly 4 incidents) in a given week, showing the λᵏ, e⁻λ, and k! terms separately.
An endpoint averages 5 requests per minute (λ = 5). Compute P(exactly 3 requests in a given minute), and separately state E[X] and Var(X) using this chapter's own mean/variance property.
A team monitors a Poisson-modeled metric (say, incidents per week) over several months and notices the observed variance is consistently much larger than the observed mean. Using this chapter's own "mean equals variance" property and its overdispersion finding, explain what this observation suggests is actually happening, and why a pure Poisson model might now be misleading for capacity/reserve planning.
📄 View solutionChapter 7 Quick Reference
- Models: the count of rare, independent events over a fixed interval, given only a rate
λ— no fixed "number of trials" needed, unlike the binomial - PMF:
P(X=k) = (λᵏ × e⁻λ) / k! - Mean = variance = λ — a distinctive, memorable property; real data showing variance far above the mean ("overdispersion") signals broken independence, often clustered events sharing a root cause
- The Poisson distribution is the limit of the binomial as
n → ∞andp → 0, withnp = λheld fixed — verified numerically to four decimal places in this chapter - Directly models server incident rates and request arrival rates — Technical Support's own
perfdiag1/incident1material, now with exact probabilities attached - Next chapter: The normal distribution and the Central Limit Theorem
The Normal Distribution & the Central Limit Theorem
Probability & Statistics Fundamentals
Chapter 8 · The Normal Distribution & the Central Limit Theorem
Chapters 6 and 7 covered discrete distributions — counting successes, counting events. The normal distribution is continuous — a measurement like response time or height can take any value along a range, not just whole numbers. It's the single most common shape in all of statistics, for a reason this chapter's second half explains directly.
The Bell Curve, Defined by Two Numbers
A normal distribution is completely determined by just two parameters: its mean μ (where the peak sits) and its standard deviation σ (how wide the spread is). Its shape is always the same symmetric bell — only the center and width change.
Z-Scores — Standardizing Any Normal Distribution
A z-score converts any value from any normal distribution into "how many standard deviations from the mean" — a universal, distribution-independent scale:
z = (x − μ) / σ
Once a value is expressed as a z-score, its probability can be looked up against the standard normal distribution (μ=0, σ=1) — the same lookup works for literally any normal distribution, regardless of its own original mean and standard deviation.
Worked Example: Server Response Times
Response times are normally distributed with μ = 200ms, σ = 30ms. What fraction of requests take longer than 260ms?
| Step | Calculation | Result |
|---|---|---|
| z-score for 260ms | (260 − 200) / 30 | z = 2 |
| Empirical rule estimate | 95% within ±2σ → 5% outside, split evenly | ≈ 2.5% above 260ms |
| Precise value | 1 − standard normal CDF(2) | ≈ 2.275% |
The empirical rule's quick estimate (2.5%) and the precise calculation (2.275%) are close, as expected — the empirical rule is a fast approximation, useful for a sanity check even when reaching for the precise number.
erf, which Python's standard library already implements — no calculus knowledge required to use it correctly.
The Central Limit Theorem
Here's the genuinely remarkable part: it doesn't matter what the underlying distribution looks like. Take repeated samples of size n from any distribution — normal, Poisson, wildly skewed, anything with a finite mean and variance — and compute each sample's own average. As n grows, the distribution of those averages approaches a normal distribution, centered on the true population mean.
n drawn from a distribution with mean μ and variance σ², the sample mean's own distribution approaches Normal(μ, σ²/n) as n grows — regardless of the original distribution's shape.
That σ²/n term is the key: the sample mean's own variance shrinks as n grows, meaning larger samples produce averages that cluster more and more tightly around the true mean.
Illustrating with a single die roll (X, uniform, not remotely normal): Var(X) = 35/12 ≈ 2.917.
| Sample size n | Var(sample mean) = σ²/n | SD(sample mean) |
|---|---|---|
| 10 | 0.2917 | ≈ 0.540 |
| 100 | 0.02917 | ≈ 0.171 |
σ/√n quantity — the standard deviation of a sample mean — has its own name, standard error, and it's the direct foundation of confidence intervals: Probability & Statistics Fundamentals' own sibling course, Statistical Inference & Applied Statistics, builds its entire second chapter on precisely this idea.
The Normal Distribution & CLT in Code
Hands-On Exercises
Request latency is normally distributed with μ = 150ms, σ = 20ms. Compute the z-score for 110ms, use the empirical rule to estimate the probability of a request taking less than 110ms, then compute the precise probability using the standard normal CDF. Compare the two estimates.
A metric has a population standard deviation of σ = 6. Using this chapter's own standard error formula, compute the standard deviation of the sample mean for sample sizes n = 9, n = 36, and n = 144. Describe the pattern you notice in how much n has to grow to halve the standard error.
Chapter 5's own weekly-incident-cost example had a highly skewed distribution (mean $1,500, standard deviation ≈ $7,057) — nothing close to a normal bell curve. Using this chapter's own Central Limit Theorem, explain why the average cost computed across many independent weeks would behave far more predictably (more tightly clustered, more normally shaped) than any single week's own cost, even though individual weeks are wildly unpredictable.
📄 View solutionChapter 8 Quick Reference
- Normal distribution: a continuous, symmetric bell curve fully defined by
μ(mean) andσ(standard deviation) - Empirical rule: ≈68% within 1σ, ≈95% within 2σ, ≈99.7% within 3σ
- Z-score:
z = (x − μ) / σ— converts any normal value onto the universal standard normal scale - Precise probabilities come from the standard normal CDF (via
math.erfin Python) — no calculus knowledge required to use it - Central Limit Theorem: the sample mean's distribution approaches Normal(μ, σ²/n) as n grows, regardless of the original distribution's shape
- Standard error (
σ/√n) is the sample mean's own standard deviation — shrinks as sample size grows, and is the direct foundation of confidence intervals in this subject's own next course - Next chapter: Descriptive statistics — mean, median, variance & standard deviation
Descriptive Statistics: Mean, Median, Variance & Standard Deviation
Probability & Statistics Fundamentals
Chapter 9 · Descriptive Statistics: Mean, Median, Variance & Standard Deviation
Every chapter so far started with a known model and predicted outcomes — the probability direction from Chapter 1's own opening table. This chapter finally works the other way: given real, already-collected data, how do you summarize it fairly? This is genuinely different math from Chapter 5's variance, not just a repeat of it — Chapter 5 computed statistics from a known theoretical distribution; this chapter computes them directly from actual numbers you've measured.
Mean & Median
The mean is the familiar average: sum every value, divide by the count. The median is the middle value once the data is sorted — the average of the two middle values if there's an even count.
mean = (Σ x) / n median = the middle value of the sorted data (average of the two middle values if n is even)
Worked Example: When One Slow Request Skews Everything
Seven real request response times (ms): 120, 115, 130, 125, 118, 122, 890 — six ordinary requests, and one genuinely slow one.
| Dataset | Mean | Median |
|---|---|---|
| All 7 values (with the 890ms outlier) | 231.43ms | 122ms |
| Just the 6 ordinary values | 121.67ms | 121ms |
Sample Variance & Standard Deviation
Chapter 5 defined variance for a known random variable: Var(X) = E[X²] − (E[X])². For real, already-collected sample data, the formula looks similar but has one crucial, easy-to-miss difference:
s² = Σ(x − x̄)² / (n − 1) s = √s² (sample standard deviation)
n would use the sample's own mean (x̄, estimated from the same limited data) as if it were the true population mean — and a sample's mean is, by construction, the value that minimizes the sum of squared deviations for that specific sample, which means dividing by n systematically underestimates the true population variance. Dividing by n − 1 instead corrects for that bias. In practice, unless you genuinely have every single data point that will ever exist (the entire population, not a sample of it), n − 1 is almost always the correct choice.
Applying this to the same two datasets from above:
| Dataset | Sample variance (s²) | Sample std dev (s) |
|---|---|---|
| All 7 values (with outlier) | 84,357.29 | ≈ 290.44ms |
| Just the 6 ordinary values | 28.27 | ≈ 5.32ms |
Variance and standard deviation are hit even harder by the outlier than the mean was — the single 890ms value inflates the standard deviation more than fiftyfold, from ≈5.32ms to ≈290ms. Squaring deviations, as the formula does, punishes large outliers disproportionately.
Descriptive Statistics in Code
Hands-On Exercises
CPU usage samples from six consecutive checks (%): 45, 48, 50, 47, 46, 95. Compute the mean and the median. Which one better represents a "typical" reading from this dataset, and why, per this chapter's own outlier-resistance finding?
Given the sample 10, 12, 14, compute the mean, then the sample variance using this chapter's own n − 1 formula, showing each squared deviation separately, and finally the sample standard deviation.
Explain, in your own words, why a data engineer analyzing a sample of 10,000 user sessions out of millions that occurred should almost always use the n − 1 sample variance formula rather than dividing by n — and describe the one specific circumstance (per this chapter's own Bessel's-correction explanation) where dividing by plain n would actually be the mathematically correct choice instead.
Chapter 9 Quick Reference
- Mean: sum divided by count; median: the middle value of sorted data — far more resistant to outliers than the mean
- A single extreme outlier can drag the mean dramatically while barely moving the median — the exact mechanism behind the "average hides a real spike" dashboard trap named in Chapter 1
- Sample variance:
s² = Σ(x−x̄)² / (n−1)— divides byn−1(Bessel's correction), notn, whenever the data is a sample rather than the entire population - Squaring deviations means variance and standard deviation are even more sensitive to outliers than the mean is
- This chapter's statistics are computed from real, already-collected data — distinct from Chapter 5's variance of a known theoretical random variable
- Next chapter: Capstone — probability & statistics in practice
Capstone — Probability & Statistics in Practice
Probability & Statistics Fundamentals
Chapter 10 · Capstone — Probability & Statistics in Practice
One continuous worked project, touching every chapter of this course in the order a real engineer would actually reach for each idea: monitoring the canary rollout of a new checkout feature, from the first hour's error logs through the final response-time analysis.
A Full Worked Rollout — Monitoring a New Checkout Feature
Two problem types are logged per session: A = "UI error" (P(A) = 0.03) and B = "timeout" (P(B) = 0.02), with P(A ∩ B) = 0.005 — some sessions hit both. The union rule gives the overall "any problem" rate: P(A ∪ B) = 0.03 + 0.02 − 0.005 = 0.045. The complement rule then gives the genuinely useful number: P(clean session) = 1 − 0.045 = 0.955 — 95.5% of sessions have no problem at all.
Testing independence: P(A) × P(B) = 0.03 × 0.02 = 0.0006, but the actual P(A ∩ B) = 0.005 — over eight times larger. They are clearly not independent. Computing P(timeout | UI error) = 0.005 / 0.03 ≈ 16.7% — far above the 2% baseline timeout rate — confirms the two problems cluster together, consistent with a shared root cause like server overload rather than two unrelated glitches.
A monitoring alert fires when the problem rate spikes. Genuine load issues happen on 5% of days (P(load) = 0.05); the alert catches 90% of real load issues (P(alert|load) = 0.9) but also false-fires on 3% of normal days (P(alert|no load) = 0.03). By the law of total probability, P(alert) = (0.9)(0.05) + (0.03)(0.95) = 0.0735. Bayes' Theorem then gives P(load | alert) = 0.045 / 0.0735 ≈ 61.2% — a meaningfully informative alert, though still short of certainty, exactly the base-rate reasoning Chapter 4 built.
The rollout's cost, as a random variable: P(no rollback) = 0.85 (cost $0), P(partial rollback) = 0.12 (cost $3,000), P(full rollback) = 0.03 (cost $40,000). Expected value: E[X] = 0(0.85) + 3,000(0.12) + 40,000(0.03) = 360 + 1,200 = $1,560 — the number the team should actually budget for, not the (much lower) most-likely single outcome.
Reusing Chapter 6's own conversion rate, p = 0.2, for n = 10 canary users: what's the probability at least half convert (X ≥ 5)? Summing the binomial PMF from k = 5 to 10 gives P(X ≥ 5) ≈ 0.033 (3.3%). If the canary group actually shows 5 or more conversions, that's a genuinely rare result under the existing 20% rate — real evidence the new feature may be improving conversion, not just random noise.
Reusing Chapter 7's own incident rate, λ = 3 per week: what's the probability of at least 2 incidents during the rollout's first monitored week? P(X ≥ 2) = 1 − P(X=0) − P(X=1) = 1 − 0.0498 − 0.1494 ≈ 0.801 (80.1%) — a week with two or more incidents is actually the normal case at this rate, not a red flag on its own.
Reusing Chapter 8's own response-time model, μ = 200ms, σ = 30ms: the probability a request falls between 170ms and 230ms (within 1σ either side) is P(170 < X < 230) ≈ 0.6827 — matching the empirical rule's 68% directly. For a monitoring dashboard averaging 100 requests at a time, the Central Limit Theorem gives that average's own standard error: SE = 30/√100 = 3ms — the averaged metric is far more stable than any single request's own time, exactly why dashboards average in the first place.
Reusing Chapter 9's own seven sampled response times — 120, 115, 130, 125, 118, 122, 890 — one request during the rollout was genuinely slow. Mean: 231.43ms. Median: 122ms. Reporting "average response time: 231ms" to stakeholders would badly misrepresent what most users actually experienced — the median, far less shaken by the single outlier, is the honest number to lead with.
This is, in essence, exactly what a real feature-rollout review looks like — every step traceable to a specific chapter of this course, none of it abstract math floating free of the actual monitoring dashboard.
What This Course Doesn't Cover
In the interest of an honest accounting: sampling and confidence intervals, hypothesis testing and A/B testing, and correlation, regression, and Bayesian updating were all named in Chapter 1 as deliberately out of scope, reserved for this subject's own next course, Statistical Inference & Applied Statistics. This course built the probability vocabulary and distributions every one of those techniques is built on top of, not a substitute for them.
This Course's Throughline, Restated
Where This Course Connects
This course is the direct foundation under Technical Support's own diagnostic material — perfdiag1's and incident1's handling of incident rates and monitoring dashboards is exactly Chapters 7–9's territory, applied without the underlying math ever being named explicitly there. Within this subject's own next course, Statistical Inference & Applied Statistics builds directly on this course's Chapter 8 (the Central Limit Theorem feeds its own sampling-distribution chapter) and Chapter 4 (Bayes' Theorem feeds its own Bayesian-updating chapter) — nothing here was built in isolation from where this subject is actually headed next.
Hands-On Exercises
A different rollout logs two problem types with P(A) = 0.04, P(B) = 0.025, and P(A ∩ B) = 0.001. Using this chapter's own Step 1–2 techniques, compute P(clean session), then determine whether A and B are independent.
Reusing Step 4's rollback-cost distribution, suppose the "full rollback" probability is revised upward to 0.05 (with "partial rollback" correspondingly reduced to 0.10, and "no rollback" still 0.85). Recompute E[X], and state whether the team's budget should increase or decrease compared to Step 4's original $1,560 figure.
For each of the eight steps in this chapter's own worked rollout, name the specific probability/statistics topic it relied on, without looking back at the step labels — just from the description of what each step actually does.
📄 View solutionChapter 10 Quick Reference
- Full worked project: union/complement rules (Ch.2) → conditional probability & independence (Ch.3) → Bayes' Theorem (Ch.4) → expected value (Ch.5) → binomial (Ch.6) → Poisson (Ch.7) → normal distribution & CLT (Ch.8) → descriptive statistics (Ch.9)
- Out of scope: sampling/confidence intervals, hypothesis testing/A-B testing, and correlation/regression/Bayesian updating — all reserved for Statistical Inference & Applied Statistics
- This course's throughline: a small, reusable toolkit for reasoning forward from a known model to precise statements about likely outcomes
- This course is the direct foundation under Technical Support's own
perfdiag1/incident1material, and under this subject's own next course - Course complete — Probability & Statistics Fundamentals, 10 chapters, from sample spaces to descriptive statistics