CrunchAcademy · K-12

Math for Data Science · MDS-5

Probability

Reason about uncertainty the way data scientists do — from coin flips to the Central Limit Theorem, simulated in code.

Probability is the language data scientists use to describe uncertainty, model randomness, and justify inference. This course builds the subject from axioms through the Central Limit Theorem, pairing each idea with a hands-on simulation in Python (NumPy/SciPy) or R. By the end you can model real-world randomness, compute and interpret distributions, and explain why sample averages behave the way they do.

PrereqsMDS-1 Math Foundations for Data Science
Code inPython (NumPy/SciPy)R
7Units
42Lessons
126Worked examples

Course Outline

MDS-5 — units

Every lesson is self-contained: a full explanation, worked step-by-step examples (in Python and R/Julia), common mistakes, a try-it-yourself, and an interactive quiz. Jump to a unit:

Weeks 1-2 Unit 1: Sample Spaces & Axioms
model-sample-spaceapply-probability-axiomscompute-equally-likelyapply-combinatoricsapply-inclusion-exclusionsimulate-set-operations
Lecture
Outcomes, sample spaces, and events

Before computing any probability you must precisely describe what can happen. This lesson sets up the vocabulary of outcomes, sample spaces, and events.

An experiment is any process with an uncertain result. Each indivisible result is an outcome, and the set of all possible outcomes is the sample space, written Omega (or S). An event is any subset of the sample space — a collection of outcomes we care about, such as 'the roll is even.' The event occurs whenever the realized outcome belongs to that subset. Sample spaces can be finite (a die roll), countably infinite (number of coin flips until a head), or continuous (a waiting time). In data science this framing is the foundation of every probabilistic model: classifiers partition an outcome space into label events, and A/B tests treat each user as an outcome. Getting the sample space right — listing outcomes at the correct granularity and ensuring they are exhaustive and mutually exclusive — is what makes later probability calculations valid.

Worked Example 1

Problem. A fair coin is flipped once. Write the sample space and the event 'heads.'

  1. Identify all indivisible outcomes: heads (H) or tails (T).
  2. Sample space Omega = {H, T}, with 2 outcomes.
  3. The event 'heads' is the subset A = {H}.
  4. P(A) = favorable / total = 1/2.

Answer. Omega = {H, T}; A = {H}; P(A) = 1/2.

Worked Example 2

Problem. Two distinguishable dice are rolled. Describe the sample space and the event 'the sum is 7.'

  1. Each die has 6 faces, and rolls are independent, so Omega has 6 x 6 = 36 ordered pairs (i, j).
  2. List pairs summing to 7: (1,6),(2,5),(3,4),(4,3),(5,2),(6,1) — that is 6 outcomes.
  3. The event E = {(1,6),(2,5),(3,4),(4,3),(5,2),(6,1)}.
  4. P(E) = 6/36 = 1/6.

Answer. |Omega| = 36; P(sum = 7) = 6/36 = 1/6.

Worked Example 3

Problem. Flip a coin until the first head appears. What does the sample space look like, and what is the event 'it takes an even number of flips'?

  1. Outcomes are sequences ending in the first H: H, TH, TTH, TTTH, ... so Omega is countably infinite.
  2. Encode each outcome by the flip count k = 1, 2, 3, ...
  3. Even-count event = {2, 4, 6, ...}, i.e. {TH, TTTH, ...}.
  4. Using P(k) = (1/2)^k, P(even) = (1/2)^2 + (1/2)^4 + ... = (1/4)/(1 - 1/4) = 1/3.

Answer. Omega is countably infinite; P(even number of flips) = 1/3.

Common mistakes
  • Confusing an outcome with an event. An outcome is a single result; an event is a set of outcomes. {H} is an event containing the outcome H.
  • Building a sample space whose outcomes overlap or are not equally detailed. Outcomes must be mutually exclusive and collectively exhaustive before you assign probabilities.
  • Assuming every sample space is finite. Waiting-time and counting experiments need countably infinite or continuous sample spaces.
✎ Try it yourself

Problem. A family has two children. Treating boy/girl as equally likely and birth order as distinguishable, write the sample space and find the probability of exactly one girl.

Solution. Omega = {BB, BG, GB, GG}, 4 equally likely outcomes. 'Exactly one girl' = {BG, GB}, which has 2 outcomes. P = 2/4 = 1/2.

The three axioms of probability

Probability is not arbitrary — it obeys three rules from which every other formula follows. This lesson states Kolmogorov's axioms and shows what they let you derive.

Kolmogorov's axioms define a probability measure P on a sample space. Axiom 1 (non-negativity): P(A) >= 0 for every event A. Axiom 2 (normalization): P(Omega) = 1. Axiom 3 (countable additivity): for disjoint events A1, A2, ..., P(A1 or A2 or ...) = sum of P(Ai). From these three rules everything else follows: P(empty set) = 0, P(A complement) = 1 - P(A), monotonicity (if A is a subset of B then P(A) <= P(B)), and the bound P(A) <= 1. In data science these axioms guarantee that any model outputting probabilities — softmax scores, calibrated classifiers, Bayesian posteriors — is internally consistent. When a model's predicted class probabilities fail to sum to 1 or go negative, it has violated an axiom, signaling a bug or a need for normalization.

Worked Example 1

Problem. If P(A) = 0.7, what is P(not A)?

  1. A and its complement are disjoint and together form Omega.
  2. By axioms 2 and 3, P(A) + P(not A) = P(Omega) = 1.
  3. So P(not A) = 1 - 0.7.

Answer. P(not A) = 0.3.

Worked Example 2

Problem. A loaded die gives P(1)=0.1, P(2)=0.1, P(3)=0.2, P(4)=0.2, P(5)=0.2. Find P(6) and P(roll <= 3).

  1. The six outcomes are disjoint and exhaust Omega, so their probabilities sum to 1.
  2. 0.1+0.1+0.2+0.2+0.2 = 0.8, so P(6) = 1 - 0.8 = 0.2.
  3. P(roll <= 3) = P(1)+P(2)+P(3) = 0.1+0.1+0.2 = 0.4 by additivity.

Answer. P(6) = 0.2; P(roll <= 3) = 0.4.

Worked Example 3

Problem. Show that if A is a subset of B then P(A) <= P(B).

  1. Write B as the disjoint union of A and (B minus A).
  2. By additivity, P(B) = P(A) + P(B minus A).
  3. By non-negativity, P(B minus A) >= 0.
  4. Therefore P(B) = P(A) + (non-negative) >= P(A).

Answer. Monotonicity: A subset of B implies P(A) <= P(B).

Common mistakes
  • Thinking probabilities must be strictly between 0 and 1. They can equal 0 or 1; the axioms only forbid negatives and totals above 1.
  • Applying additivity to overlapping events. P(A or B) = P(A) + P(B) only when A and B are disjoint; otherwise subtract the overlap.
  • Forgetting normalization. A set of non-negative numbers is a probability assignment only if it sums (or integrates) to exactly 1.
✎ Try it yourself

Problem. A spinner lands in region A with probability 0.45 and region B with 0.35; the rest is region C. Regions are disjoint. Find P(C) and P(A or C).

Solution. P(C) = 1 - 0.45 - 0.35 = 0.20. A and C are disjoint, so P(A or C) = 0.45 + 0.20 = 0.65.

Equally likely outcomes and counting

When every outcome is equally likely, probability reduces to counting. This lesson formalizes the favorable-over-total rule and its assumptions.

In the equally likely (classical) model, a finite sample space has every outcome carrying the same probability 1/|Omega|. Then for any event A, P(A) = |A| / |Omega| = (favorable outcomes) / (total outcomes). This reduces probability to combinatorics: count the ways an event can happen and divide by the total. The model is only valid when symmetry justifies equal likelihood — fair dice, well-shuffled cards, random sampling. In data science, the equally likely assumption underlies uniform random sampling, train/test splitting, and permutation tests, where each arrangement of labels is treated as equally probable under the null hypothesis. The core skill is careful counting: deciding whether order matters and whether repetition is allowed determines which counting rule applies.

Worked Example 1

Problem. Draw one card from a standard 52-card deck. What is the probability it is a heart?

  1. Each card is equally likely, so |Omega| = 52.
  2. There are 13 hearts, so |A| = 13.
  3. P(heart) = 13/52 = 1/4.

Answer. P(heart) = 1/4.

Worked Example 2

Problem. Roll two fair dice. What is the probability the two faces are equal (a 'double')?

  1. |Omega| = 36 equally likely ordered pairs.
  2. Doubles: (1,1),(2,2),(3,3),(4,4),(5,5),(6,6) — 6 outcomes.
  3. P(double) = 6/36 = 1/6.

Answer. P(double) = 1/6.

Worked Example 3

Problem. From 5 distinct books, 2 are chosen at random. What is the probability a specific book (say, the dictionary) is among them?

  1. Total ways to choose 2 of 5 (order irrelevant) = 5 choose 2 = 10.
  2. Favorable: the dictionary is fixed, choose 1 more from the remaining 4 = 4 ways.
  3. P = 4/10 = 2/5.

Answer. P(dictionary chosen) = 2/5 = 0.4.

Common mistakes
  • Using favorable/total when outcomes are NOT equally likely (e.g., a loaded die). The formula only holds under symmetry.
  • Mismatching the order convention in numerator and denominator. Count both favorable and total either with order or without order — be consistent.
  • Double-counting outcomes. Make sure your list of favorable outcomes has no repeats and your total has no omissions.
✎ Try it yourself

Problem. A bag has 4 red and 6 blue marbles. One marble is drawn at random. What is the probability it is red?

Solution. All 10 marbles are equally likely. Favorable (red) = 4, total = 10. P(red) = 4/10 = 2/5 = 0.4.

Permutations, combinations, and the binomial coefficient

Counting outcomes systematically requires knowing when order matters. This lesson covers permutations, combinations, and the binomial coefficient n choose k.

Counting rules answer 'how many ways?' The multiplication principle says independent choices multiply. A permutation is an ordered arrangement: the number of ways to order all n distinct objects is n!, and the number of ordered selections of k from n is P(n,k) = n!/(n-k)!. A combination is an unordered selection of k from n, counted by the binomial coefficient C(n,k) = n choose k = n!/(k!(n-k)!), which divides out the k! orderings that a permutation would count separately. Combinations power the binomial distribution, feature-subset selection, and bootstrap/permutation resampling in data science. The decisive question is always: does order matter? If yes, use permutations; if no, use combinations.

Worked Example 1

Problem. How many ways can 4 runners finish a race (no ties)?

  1. Order matters (1st, 2nd, 3rd, 4th) and all 4 are arranged.
  2. Number of orderings = 4! = 4 x 3 x 2 x 1.
  3. = 24.

Answer. 24 finishing orders.

Worked Example 2

Problem. How many distinct 5-card poker hands can be dealt from 52 cards?

  1. Order within a hand does not matter, so use combinations.
  2. C(52,5) = 52!/(5! * 47!).
  3. = (52 x 51 x 50 x 49 x 48)/(5 x 4 x 3 x 2 x 1) = 311,875,200 / 120.
  4. = 2,598,960.

Answer. 2,598,960 hands.

Worked Example 3

Problem. A committee of 3 is chosen from 4 women and 5 men. What is the probability it has exactly 2 women?

  1. Total committees: C(9,3) = 84.
  2. Choose 2 women from 4: C(4,2) = 6. Choose 1 man from 5: C(5,1) = 5.
  3. Favorable = 6 x 5 = 30.
  4. P = 30/84 = 5/14 ≈ 0.357.

Answer. P(exactly 2 women) = 5/14 ≈ 0.357.

Common mistakes
  • Using permutations when order is irrelevant. A committee {A,B} is the same as {B,A}; use combinations, which divide by k!.
  • Forgetting that C(n,k) = C(n, n-k). Choosing which k to include is the same as choosing which n-k to exclude.
  • Mixing the multiplication principle incorrectly — multiply counts of independent stages, do not add them.
✎ Try it yourself

Problem. How many ways can you choose a 3-topping pizza from 8 available toppings (no repeats, order irrelevant)?

Solution. Order does not matter, so use C(8,3) = 8!/(3!5!) = (8 x 7 x 6)/(3 x 2 x 1) = 336/6 = 56 ways.

Unions, intersections, and the inclusion-exclusion principle

When events overlap, you cannot simply add their probabilities. Inclusion-exclusion corrects for the double-counted overlap.

For two events, P(A or B) = P(A) + P(B) - P(A and B): adding P(A) and P(B) counts the overlap A and B twice, so we subtract it once. This is the inclusion-exclusion principle. For three events it extends to P(A or B or C) = sum of singles - sum of pairwise intersections + the triple intersection, alternating signs. The intersection A and B is the event that both occur; the union A or B is the event that at least one occurs. When events are disjoint, P(A and B) = 0 and inclusion-exclusion collapses to plain addition. In data science this principle appears in computing the probability that at least one of several rare failures occurs, in set-based deduplication, and in reasoning about overlapping filters or query conditions.

Worked Example 1

Problem. P(A) = 0.6, P(B) = 0.5, P(A and B) = 0.3. Find P(A or B).

  1. Apply inclusion-exclusion: P(A or B) = P(A) + P(B) - P(A and B).
  2. = 0.6 + 0.5 - 0.3.
  3. = 0.8.

Answer. P(A or B) = 0.8.

Worked Example 2

Problem. Draw one card from 52. What is the probability it is a king OR a heart?

  1. P(king) = 4/52, P(heart) = 13/52.
  2. Overlap (king of hearts) = 1/52.
  3. P(king or heart) = 4/52 + 13/52 - 1/52 = 16/52.
  4. = 4/13 ≈ 0.308.

Answer. P(king or heart) = 16/52 = 4/13.

Worked Example 3

Problem. Of 100 learners, 60 take math, 45 take statistics, and 25 take both. How many take at least one of the two?

  1. Let M and S be the two course events (here as counts).
  2. |M or S| = |M| + |S| - |M and S| = 60 + 45 - 25.
  3. = 80 learners.
  4. As a probability for a random learner, P(at least one) = 80/100 = 0.8.

Answer. 80 learners; P(at least one) = 0.8.

Common mistakes
  • Adding P(A) + P(B) without subtracting the overlap when events are not disjoint. This overcounts and can exceed 1.
  • Confusing 'and' with 'or'. Intersection is both occurring; union is at least one occurring.
  • For three events, forgetting to add the triple intersection back after subtracting the pairwise overlaps.
✎ Try it yourself

Problem. In a survey, 70% of people like coffee, 40% like tea, and 30% like both. What fraction likes coffee or tea?

Solution. P(coffee or tea) = 0.70 + 0.40 - 0.30 = 0.80. So 80% like at least one of the two.

Set theory and probability rules in code

Probability rules map directly onto set operations, which Python and R can simulate. This lesson turns the algebra into reproducible code.

Events are sets, and probability rules are set operations: union (or), intersection (and), and complement (not). Two computational approaches verify these rules. The analytic approach represents the sample space and events as Python sets or R vectors and counts directly. The Monte Carlo approach simulates the experiment many times and estimates P(A) as the fraction of trials in which A occurs; by the Law of Large Numbers this estimate converges to the true probability. Simulation is invaluable when a sample space is too large or complex to enumerate, which is the common case in real data science. The key practice is to define an event as a boolean condition on simulated outcomes, then average the boolean array to get an empirical probability.

Worked Example 1

Problem. Using set operations on a die {1..6}, verify P(even or >4).

  1. Even = {2,4,6}, >4 = {5,6}.
  2. Union = {2,4,5,6}, size 4.
  3. P = 4/6 = 2/3 ≈ 0.667.

Answer. P(even or >4) = 2/3.

Worked Example 2

Problem. Estimate P(sum = 7) for two dice by simulation in Python and compare to the exact 1/6.

  1. Exact value computed earlier is 6/36 = 0.1667.
  2. Simulate many paired rolls and compute the fraction with sum 7.
  3. Code: import numpy as np; rng = np.random.default_rng(0); d = rng.integers(1,7,(1_000_000,2)); print((d.sum(1)==7).mean())
  4. Result: 0.16689 (≈ 0.1667), matching the exact value within simulation error.

Answer. Simulated ≈ 0.1669 vs exact 0.1667.

Worked Example 3

Problem. Verify the complement rule P(not A) = 1 - P(A) for 'sum >= 4' on two dice using R.

  1. Enumerate all 36 outcomes with expand.grid.
  2. Code: g <- expand.grid(1:6,1:6); s <- g[,1]+g[,2]; mean(s>=4) gives 0.9167; 1-mean(s<4) gives 0.9167.
  3. P(sum<4)=P({2,3 as totals}): totals 2 and 3 occur 1+2=3 times, so 3/36=0.0833.
  4. 1 - 0.0833 = 0.9167, confirming the complement rule.

Answer. P(sum>=4) = 0.9167 = 1 - 0.0833.

Common mistakes
  • Treating a Monte Carlo estimate as exact. It carries sampling error of order 1/sqrt(N); increase N to tighten it.
  • Not fixing a random seed, making results non-reproducible. Use np.random.default_rng(seed) or set.seed() in R.
  • Confusing element membership with subset relations when coding events; an event is a set of outcomes, not a single outcome.
✎ Try it yourself

Problem. Write a one-line NumPy estimate of P(at least one 6 in two dice rolls) and state the exact value.

Solution. Exact: P(at least one 6) = 1 - (5/6)^2 = 1 - 25/36 = 11/36 ≈ 0.3056. Code: rng=np.random.default_rng(1); d=rng.integers(1,7,(1_000_000,2)); print((d==6).any(1).mean()) gives ≈ 0.3057, matching.

Key terms
  • Sample space — the set of all possible outcomes of an experiment, often written as Omega or S.
  • Event — any subset of the sample space; the experiment 'realizes' an event when its outcome is in that subset.
  • Probability axioms — non-negativity, total probability equals 1, and countable additivity for disjoint events.
  • Equally likely outcomes — a model where every outcome has the same probability, so P(event) = favorable / total.
  • Permutation — an ordered arrangement of objects; n distinct objects arrange in n! ways.
  • Combination — an unordered selection of k objects from n, counted by the binomial coefficient n choose k.
  • Inclusion-exclusion principle — P(A or B) = P(A) + P(B) - P(A and B), generalizing to more sets.
  • Mutually exclusive (disjoint) events — events that cannot occur together, so their intersection is empty.
Assignment · Estimate vs. compute: the birthday problem

Compute the exact probability that at least two people in a room of n share a birthday using the equally-likely / counting model, then write a Python or R simulation that repeatedly fills a room at random and estimates the same probability. Vary n from 2 to 60 and overlay the exact curve against your simulated estimates. Explain where and why simulation error appears.

Deliverable · A script plus a short write-up showing the exact-vs-simulated curve and the smallest n for which the probability first exceeds 50%.

Quiz · 5 questions
  1. 1. Which of the following is a valid probability axiom?

  2. 2. A fair six-sided die is rolled. What is the probability of rolling an even number OR a number greater than 4?

  3. 3. How many distinct 3-person committees can be formed from 8 people?

  4. 4. For events A and B, P(A) = 0.5, P(B) = 0.4, and P(A and B) = 0.2. What is P(A or B)?

  5. 5. Two events are mutually exclusive when:

You'll be able to

I can describe an experiment with a sample space and identify events as subsets of it.

I can apply the probability axioms and inclusion-exclusion to compute event probabilities.

I can use permutations and combinations to count outcomes in equally likely settings.

Weeks 3-4 Unit 2: Conditional Probability & Bayes
compute-conditionaltest-independenceapply-total-probabilityapply-bayes-theoreminterpret-prior-posteriorreason-base-rates
Lecture
Conditional probability and the multiplication rule

Most real questions are conditional: given what we already know, how likely is something? This lesson defines conditioning and the multiplication rule that chains it.

The conditional probability of A given B, written P(A|B), is the probability that A occurs once we know B has occurred. It is defined as P(A|B) = P(A and B) / P(B), valid whenever P(B) > 0. Geometrically, conditioning on B shrinks the sample space to B and renormalizes. Rearranging gives the multiplication rule: P(A and B) = P(A|B) * P(B) = P(B|A) * P(A), which lets us chain dependent events step by step. In data science, conditioning is everywhere: a spam filter computes P(spam | words), a recommender estimates P(click | user, item), and feature engineering often encodes conditional rates. Mastering this definition is the gateway to independence, the law of total probability, and Bayes' theorem.

Worked Example 1

Problem. A card is drawn from 52. Given it is a face card (J, Q, K), what is the probability it is a king?

  1. There are 12 face cards, so condition on B = {face card}, P(B) = 12/52.
  2. Kings that are face cards: 4, so P(A and B) = 4/52.
  3. P(king | face) = (4/52) / (12/52) = 4/12.
  4. = 1/3.

Answer. P(king | face card) = 1/3.

Worked Example 2

Problem. Roll two fair dice. Given the sum is 8, what is the probability one die shows a 5?

  1. Outcomes summing to 8: (2,6),(3,5),(4,4),(5,3),(6,2) — 5 outcomes, so P(sum=8) = 5/36.
  2. Among these, a 5 appears in (3,5) and (5,3) — 2 outcomes.
  3. P(a 5 | sum=8) = (2/36) / (5/36).
  4. = 2/5 = 0.4.

Answer. P(some die = 5 | sum = 8) = 2/5.

Worked Example 3

Problem. Two cards are drawn without replacement from 52. Use the multiplication rule to find P(both aces).

  1. P(first ace) = 4/52.
  2. Given the first was an ace, P(second ace) = 3/51.
  3. P(both) = (4/52) * (3/51) = 12/2652.
  4. = 1/221 ≈ 0.00452.

Answer. P(both aces) = 1/221 ≈ 0.0045.

Common mistakes
  • Swapping the conditioning direction: P(A|B) is generally not equal to P(B|A). Reversing them is the prosecutor's fallacy.
  • Dividing by the wrong total. The denominator is P(B), the probability of the conditioning event, not P(Omega).
  • Treating dependent draws as independent. Without replacement, the second probability changes once the first outcome is known.
✎ Try it yourself

Problem. In a deck of 52, two cards are drawn without replacement. What is the probability the second card is a heart given the first was a heart?

Solution. After removing one heart, 12 hearts remain among 51 cards. P(second heart | first heart) = 12/51 = 4/17 ≈ 0.235.

Independence of events

Sometimes knowing B tells you nothing about A. This lesson defines independence precisely and shows how to test for it.

Two events A and B are independent when the occurrence of one does not change the probability of the other: P(A|B) = P(A), equivalently P(A and B) = P(A) * P(B). The product form is the most useful test because it is symmetric and handles zero-probability edge cases gracefully. Independence is not the same as being disjoint — disjoint events with positive probability are actually dependent, because knowing one occurred guarantees the other did not. Independence can extend to many events (mutual independence requires every subset to factorize). In data science, the naive Bayes classifier assumes features are conditionally independent given the class, and many statistical tests assume independent observations; checking these assumptions guards against badly biased estimates.

Worked Example 1

Problem. Two fair coins are flipped. Are 'first is heads' and 'second is heads' independent?

  1. P(first H) = 1/2, P(second H) = 1/2.
  2. P(both H) = 1/4 from the 4 equally likely outcomes {HH,HT,TH,TT}.
  3. Check: P(A)*P(B) = 1/2 * 1/2 = 1/4 = P(A and B).
  4. The product rule holds, so they are independent.

Answer. Independent: P(A and B) = 1/4 = P(A)P(B).

Worked Example 2

Problem. Draw one card. Let A = 'heart' and B = 'king'. Are A and B independent?

  1. P(A) = 13/52 = 1/4, P(B) = 4/52 = 1/13.
  2. P(A and B) = P(king of hearts) = 1/52.
  3. P(A)*P(B) = (1/4)(1/13) = 1/52.
  4. They match, so suit and rank are independent.

Answer. Independent: 1/52 = (1/4)(1/13).

Worked Example 3

Problem. Roll one die. Let A = 'even' and B = 'roll <= 2'. Are they independent?

  1. P(A) = 3/6 = 1/2, P(B) = 2/6 = 1/3.
  2. A and B = 'even and <= 2' = {2}, so P(A and B) = 1/6.
  3. P(A)*P(B) = (1/2)(1/3) = 1/6.
  4. Equal, so A and B are independent here.

Answer. Independent: P(A and B) = 1/6 = P(A)P(B).

Common mistakes
  • Confusing independent with mutually exclusive. Disjoint events (with positive probability) are dependent, since one occurring rules out the other.
  • Assuming pairwise independence implies mutual independence. All subsets must factorize for full independence.
  • Inferring independence from a small sample where the product rule appears to hold by chance; independence is a property of the model, not a noisy estimate.
✎ Try it yourself

Problem. A die is rolled. A = 'roll is a multiple of 3' = {3,6}, B = 'roll is even' = {2,4,6}. Are A and B independent?

Solution. P(A) = 2/6 = 1/3, P(B) = 3/6 = 1/2. A and B = {6}, P = 1/6. P(A)P(B) = (1/3)(1/2) = 1/6 = P(A and B). Yes, independent.

The law of total probability

To find an overall probability, average over every way it can happen. This lesson introduces partitions and the law of total probability.

A partition splits the sample space into disjoint events A1, ..., Ak that together cover everything. The law of total probability says that for any event B, P(B) = sum over i of P(B | Ai) * P(Ai). Intuitively, we weight the conditional probability of B within each piece by how likely that piece is, then add. It is the denominator engine of Bayes' theorem and the foundation of mixture models. In data science it formalizes scenarios like 'spam arrives from three sources with different rates' or 'customers belong to segments with different conversion probabilities' — you compute an overall rate by averaging segment rates weighted by segment sizes. The key is choosing a partition that makes each conditional probability easy to state.

Worked Example 1

Problem. Factory: machine A makes 60% of parts (2% defective), machine B makes 40% (5% defective). What fraction of all parts are defective?

  1. Partition by machine: P(A)=0.6, P(B)=0.4.
  2. P(def|A)=0.02, P(def|B)=0.05.
  3. P(def) = 0.02*0.6 + 0.05*0.4 = 0.012 + 0.020.
  4. = 0.032.

Answer. P(defective) = 0.032 (3.2%).

Worked Example 2

Problem. An urn has 3 red, 2 blue balls. Two are drawn without replacement. What is P(second is red)?

  1. Partition on the first draw: P(first red)=3/5, P(first blue)=2/5.
  2. P(2nd red | 1st red) = 2/4; P(2nd red | 1st blue) = 3/4.
  3. P(2nd red) = (2/4)(3/5) + (3/4)(2/5) = 6/20 + 6/20.
  4. = 12/20 = 3/5.

Answer. P(second is red) = 3/5 (same as the first, by symmetry).

Worked Example 3

Problem. Emails come from work (50%, spam rate 1%), promos (30%, spam rate 20%), unknown (20%, spam rate 60%). What is the overall spam rate?

  1. Weights: 0.5, 0.3, 0.2; spam rates: 0.01, 0.20, 0.60.
  2. P(spam) = 0.5*0.01 + 0.3*0.20 + 0.2*0.60.
  3. = 0.005 + 0.060 + 0.120.
  4. = 0.185.

Answer. Overall spam rate = 0.185 (18.5%).

Common mistakes
  • Using events that overlap or do not cover Omega. The Ai must be disjoint and exhaustive — a true partition.
  • Forgetting to weight by P(Ai). You average the conditionals weighted by how likely each branch is, not as a plain average.
  • Mixing up P(B|Ai) with P(Ai|B); the law uses the forward conditionals, while reversing them needs Bayes.
✎ Try it yourself

Problem. A box has two coins: a fair coin and a coin with P(heads)=0.8. You pick one at random and flip it. What is P(heads)?

Solution. Partition by coin: each chosen with probability 1/2. P(H) = (1/2)(0.5) + (1/2)(0.8) = 0.25 + 0.40 = 0.65.

Bayes' theorem and reversing conditionals

Bayes' theorem flips a conditional probability around, letting evidence update belief. It is the engine of probabilistic inference.

Bayes' theorem computes P(A|B) from the reverse conditional P(B|A): P(A|B) = P(B|A) * P(A) / P(B). The denominator P(B) is usually expanded with the law of total probability, P(B) = P(B|A)P(A) + P(B|not A)P(not A). The theorem reverses the direction of reasoning — from 'probability of evidence given a hypothesis' to 'probability of the hypothesis given the evidence' — which is exactly what we need when we observe data and want to infer causes. In data science Bayes underlies spam filtering, medical diagnosis, A/B test analysis, and the entire field of Bayesian inference. The recurring lesson is that the answer depends heavily on the prior P(A), not just on how diagnostic the evidence is.

Worked Example 1

Problem. A test is 90% accurate for a disease affecting 1% of people (P(pos|disease)=0.9, P(pos|healthy)=0.1). Given a positive test, what is P(disease)?

  1. Prior P(D)=0.01, P(not D)=0.99.
  2. P(pos) = 0.9*0.01 + 0.1*0.99 = 0.009 + 0.099 = 0.108.
  3. P(D|pos) = (0.9*0.01)/0.108 = 0.009/0.108.
  4. ≈ 0.0833.

Answer. P(disease | positive) ≈ 8.3%.

Worked Example 2

Problem. Two factories: A (70% of output, 1% defect), B (30%, 4% defect). A part is defective. Probability it came from B?

  1. P(def) = 0.01*0.7 + 0.04*0.3 = 0.007 + 0.012 = 0.019.
  2. P(B|def) = P(def|B)P(B)/P(def) = (0.04*0.3)/0.019.
  3. = 0.012/0.019.
  4. ≈ 0.632.

Answer. P(from B | defective) ≈ 0.632.

Worked Example 3

Problem. An email contains the word 'free'. P(free|spam)=0.6, P(free|ham)=0.05, and 20% of email is spam. P(spam|free)?

  1. P(free) = 0.6*0.2 + 0.05*0.8 = 0.12 + 0.04 = 0.16.
  2. P(spam|free) = (0.6*0.2)/0.16 = 0.12/0.16.
  3. = 0.75.

Answer. P(spam | 'free') = 0.75.

Common mistakes
  • Ignoring the prior and equating P(A|B) with P(B|A). A highly accurate test on a rare condition still yields a low posterior.
  • Forgetting the false-positive branch in the denominator. P(B) must include P(B|not A)P(not A).
  • Plugging in sensitivity but mislabeling specificity. P(pos|healthy) = 1 - specificity, not specificity itself.
✎ Try it yourself

Problem. A factory's alarm sounds for 99% of real fires but also for 2% of non-fires. Fires occur on 0.1% of days. The alarm sounds — what is P(fire)?

Solution. P(alarm) = 0.99*0.001 + 0.02*0.999 = 0.00099 + 0.01998 = 0.02097. P(fire|alarm) = 0.00099/0.02097 ≈ 0.047, about 4.7%.

Prior, likelihood, and posterior intuition

Bayes' theorem has three named pieces. Understanding prior, likelihood, and posterior turns the formula into a story of belief updating.

In Bayesian language, P(H) is the prior — your belief in hypothesis H before seeing data. P(D|H) is the likelihood — how probable the observed data D is under H. P(H|D) is the posterior — your updated belief after seeing D. Bayes' theorem reads posterior is proportional to likelihood times prior: P(H|D) proportional to P(D|H) P(H), with the evidence P(D) acting as a normalizing constant so the posterior sums to 1. The intuition is that data reweights your hypotheses by how well each predicted what you saw. Strong evidence overwhelms a weak prior; a strong prior resists weak evidence. In data science this is the backbone of Bayesian estimation, online learning, and sequential updating, where today's posterior becomes tomorrow's prior.

Worked Example 1

Problem. Two hypotheses for a coin: fair (H1) or two-headed (H2), priors 0.5 each. You flip one head. Find the posteriors.

  1. Likelihoods of one head: P(H|H1)=0.5, P(H|H2)=1.
  2. Unnormalized: H1: 0.5*0.5=0.25; H2: 1*0.5=0.5.
  3. Evidence = 0.25 + 0.5 = 0.75.
  4. Posteriors: P(H1|head)=0.25/0.75=1/3; P(H2|head)=0.5/0.75=2/3.

Answer. Posterior: fair 1/3, two-headed 2/3.

Worked Example 2

Problem. Continuing, you flip the same coin and get a second head. Update the posterior using the previous posterior as the new prior.

  1. New prior: P(H1)=1/3, P(H2)=2/3.
  2. Likelihood of a head: 0.5 and 1.
  3. Unnormalized: H1: 0.5*(1/3)=1/6; H2: 1*(2/3)=2/3.
  4. Evidence = 1/6 + 2/3 = 5/6. Posteriors: H1 = (1/6)/(5/6)=1/5; H2 = (2/3)/(5/6)=4/5.

Answer. After two heads: fair 1/5, two-headed 4/5 (same as updating from scratch with two heads).

Worked Example 3

Problem. If instead the second flip is a tail, what is the posterior?

  1. A two-headed coin can never show tails: P(tail|H2)=0.
  2. From prior (1/3, 2/3): unnormalized H1: 0.5*(1/3)=1/6; H2: 0*(2/3)=0.
  3. Evidence = 1/6.
  4. Posterior: P(H1)=1, P(H2)=0 — a single tail rules out the two-headed coin.

Answer. A tail makes the coin certainly fair: posterior fair = 1.

Common mistakes
  • Confusing likelihood with posterior. P(D|H) is not P(H|D); the likelihood is read as a function of H for fixed data.
  • Forgetting to renormalize. After multiplying likelihood by prior you must divide by the evidence so probabilities sum to 1.
  • Believing the prior never matters. With little data the prior dominates the posterior; only abundant evidence washes it out.
✎ Try it yourself

Problem. Prior that a website visitor will buy is 0.10. A visitor adds an item to cart; P(cart|buyer)=0.8, P(cart|non-buyer)=0.2. Find the posterior P(buyer|cart).

Solution. Unnormalized: buyer 0.8*0.10=0.08; non-buyer 0.2*0.90=0.18. Evidence = 0.26. Posterior P(buyer|cart) = 0.08/0.26 ≈ 0.308.

Base rates and the false-positive paradox

When a condition is rare, even an accurate test produces mostly false alarms. This lesson explains base-rate neglect and the false-positive paradox.

The base rate is the unconditional prevalence P(disease) of a condition. The false-positive paradox arises because when the base rate is very low, the small fraction of false positives among the large healthy population can outnumber the true positives among the few sick people — so a positive test still implies a low probability of disease. Formally, P(disease|positive) depends on prevalence as much as on test accuracy. Base-rate neglect is the cognitive error of judging P(disease|positive) using only the test's accuracy while ignoring how rare the disease is. In data science this is critical for imbalanced classification: a fraud or rare-disease detector with 99% accuracy can still generate overwhelmingly false alarms, which is why precision, recall, and prevalence-aware metrics matter more than raw accuracy.

Worked Example 1

Problem. Disease prevalence 0.1%. Test: sensitivity 99%, specificity 99%. Find P(disease|positive).

  1. P(D)=0.001, P(not D)=0.999.
  2. P(pos) = 0.99*0.001 + 0.01*0.999 = 0.00099 + 0.00999 = 0.01098.
  3. P(D|pos) = 0.00099/0.01098.
  4. ≈ 0.0902.

Answer. Only about 9% — false positives dominate despite 99% accuracy.

Worked Example 2

Problem. Same test, but now prevalence is 10%. Find P(disease|positive).

  1. P(D)=0.10, P(not D)=0.90.
  2. P(pos) = 0.99*0.10 + 0.01*0.90 = 0.099 + 0.009 = 0.108.
  3. P(D|pos) = 0.099/0.108.
  4. ≈ 0.917.

Answer. About 92% — a higher base rate makes the same test far more conclusive.

Worked Example 3

Problem. In a city of 1,000,000 with prevalence 0.1% and the 99%/99% test, how many positives are true vs false?

  1. Sick people: 1,000,000 * 0.001 = 1000; true positives = 0.99*1000 = 990.
  2. Healthy people: 999,000; false positives = 0.01*999,000 = 9990.
  3. Total positives = 990 + 9990 = 10,980.
  4. True-positive fraction = 990/10,980 ≈ 0.090, matching the 9% above.

Answer. 990 true vs 9990 false positives; ~9% of positives are real.

Common mistakes
  • Equating test accuracy with the chance of disease after a positive result. The posterior depends on the base rate too.
  • Reporting raw accuracy on imbalanced data. A detector predicting 'no disease' always can be 99.9% accurate yet useless.
  • Assuming a higher-accuracy test always fixes the problem. Lowering the base rate (rarer condition) erodes the posterior even for excellent tests.
✎ Try it yourself

Problem. A fraud detector flags transactions with 95% sensitivity and 98% specificity. Only 0.5% of transactions are fraud. If a transaction is flagged, what is P(fraud)?

Solution. P(flag) = 0.95*0.005 + 0.02*0.995 = 0.00475 + 0.0199 = 0.02465. P(fraud|flag) = 0.00475/0.02465 ≈ 0.193, about 19% — most flags are false alarms.

Key terms
  • Conditional probability — P(A given B) = P(A and B) / P(B), the probability of A once B is known to occur.
  • Multiplication rule — P(A and B) = P(A given B) * P(B), used to chain dependent events.
  • Independence — A and B are independent when P(A and B) = P(A) * P(B), so one tells you nothing about the other.
  • Law of total probability — P(B) = sum over a partition of P(B given A_i) * P(A_i).
  • Bayes' theorem — P(A given B) = P(B given A) * P(A) / P(B), reversing the direction of conditioning.
  • Prior — the probability assigned to a hypothesis before observing new evidence.
  • Posterior — the updated probability of a hypothesis after incorporating evidence via Bayes.
  • Base rate — the unconditional prevalence of an event, easily neglected when judging conditional outcomes.
Assignment · Disease screening with Bayes

A disease affects 1% of a population. A test has 99% sensitivity and 95% specificity. Use Bayes' theorem to compute the probability that a person who tests positive actually has the disease. Then write a Python or R simulation that generates a large population, applies the test, and empirically estimates the same posterior. Compare the analytic and simulated answers and explain the base-rate effect.

Deliverable · A notebook or script reporting the analytic posterior, the simulated posterior, and a one-paragraph explanation of why the number is surprisingly low.

Quiz · 5 questions
  1. 1. If P(A) = 0.3, P(B) = 0.5, and A and B are independent, what is P(A and B)?

  2. 2. Bayes' theorem lets you compute which quantity from the others?

  3. 3. P(A given B) = 0.4, P(B) = 0.5. What is P(A and B)?

  4. 4. In the disease-screening example, the main reason a positive test often means low disease probability is:

  5. 5. Which statement is true if A and B are independent?

You'll be able to

I can compute conditional probabilities and decide whether two events are independent.

I can apply the law of total probability and Bayes' theorem to update beliefs from evidence.

I can explain why a positive medical test can still mean a low chance of disease.

Weeks 5-6 Unit 3: Random Variables
define-random-variabledistinguish-discrete-continuoususe-pmfuse-pdfuse-cdftransform-random-variable
Lecture
From outcomes to random variables

Working with raw outcomes is clumsy; attaching numbers to them lets us do arithmetic. This lesson defines a random variable as that numeric bridge.

A random variable X is a function that maps each outcome in the sample space to a real number. It does not 'vary randomly' on its own — the randomness lives in which outcome occurs, and X simply reports a number for that outcome. For two coin flips, X = number of heads sends HH to 2, HT and TH to 1, and TT to 0. Once outcomes carry numbers we can ask P(X = 1), P(X <= 1), compute averages, and compare experiments on a common numeric scale. In data science nearly every quantity we model — a click count, a purchase amount, a sensor reading — is a random variable summarizing a complicated underlying experiment. Choosing what to measure (the function g) is itself a modeling decision that determines which distribution and tools apply later.

Worked Example 1

Problem. Flip two fair coins. Define X = number of heads and find the probability distribution of X.

  1. Sample space {HH, HT, TH, TT}, each with probability 1/4.
  2. Map outcomes: HH->2, HT->1, TH->1, TT->0.
  3. P(X=0)=1/4, P(X=1)=2/4=1/2, P(X=2)=1/4.
  4. Check the probabilities sum to 1: 1/4 + 1/2 + 1/4 = 1.

Answer. P(X=0)=0.25, P(X=1)=0.50, P(X=2)=0.25.

Worked Example 2

Problem. Roll two dice and let S be the sum. Find P(S = 5).

  1. The 36 ordered outcomes are equally likely.
  2. Outcomes with sum 5: (1,4),(2,3),(3,2),(4,1) — 4 of them.
  3. P(S=5) = 4/36.
  4. = 1/9 ≈ 0.111.

Answer. P(S = 5) = 1/9 ≈ 0.111.

Worked Example 3

Problem. A point lands uniformly in [0,1]. Define X = 1 if the point is in [0, 0.3] else 0. What kind of variable is X and what is P(X=1)?

  1. X maps a continuous outcome to {0,1}, so X is a discrete (indicator) random variable.
  2. P(X=1) = length of [0,0.3] = 0.3.
  3. P(X=0) = 0.7.
  4. A continuous experiment can produce a discrete random variable through such a mapping.

Answer. X is a discrete indicator with P(X=1)=0.3, P(X=0)=0.7.

Common mistakes
  • Thinking the random variable is itself random. The function is fixed; randomness comes from the outcome that gets plugged in.
  • Confusing the value x with the variable X. X is the rule; x is a particular number it can equal.
  • Forgetting that several outcomes can map to the same value, so P(X=x) sums the probabilities of all outcomes sending to x.
✎ Try it yourself

Problem. Flip three fair coins and let X = number of heads. Find P(X = 2).

Solution. There are 2^3 = 8 equally likely outcomes. Exactly two heads: HHT, HTH, THH — 3 outcomes. P(X=2) = 3/8 = 0.375.

Discrete vs. continuous random variables

The first fork in modeling any quantity is whether it is counted or measured. This lesson contrasts discrete and continuous random variables.

A discrete random variable takes values in a countable set — typically integers from counting — and assigns positive probability to individual values via a probability mass function. A continuous random variable takes values across an interval of the real line and is described by a probability density function; any single exact value has probability zero, and probabilities come from areas (integrals) over ranges. The dividing question is whether the quantity is counted (number of defects, clicks, arrivals) or measured on a continuum (time, height, temperature). Some quantities are mixed, but most data-science models pick one. The distinction governs every downstream tool: PMF versus PDF, sums versus integrals, and which SciPy or R function family (e.g. binom vs norm) you reach for. Misclassifying a variable leads to using the wrong probability calculus.

Worked Example 1

Problem. Classify: (a) number of emails per hour, (b) exact wait time for a bus.

  1. Number of emails is a count taking 0,1,2,... so it is discrete.
  2. Wait time is measured on a continuum (e.g. 4.37 minutes), so it is continuous.
  3. Discrete -> PMF; continuous -> PDF.

Answer. (a) discrete, (b) continuous.

Worked Example 2

Problem. For a continuous variable, why is P(X = 5) = 0, and how do we get a nonzero probability?

  1. Probability is area under the PDF over an interval.
  2. A single point has zero width, so its area is 0; hence P(X = 5) = 0.
  3. Use a range: P(4.9 <= X <= 5.1) = integral of the density over that interval > 0.
  4. This is why we report intervals, not exact values, for continuous data.

Answer. Point probability is 0; use an interval's area for a positive probability.

Worked Example 3

Problem. A variable X is uniform on {1,2,3,4,5}. Is it discrete or continuous, and what is P(X = 3)?

  1. Values form a finite set, so X is discrete.
  2. Discrete uniform: each value equally likely, P = 1/5.
  3. P(X = 3) = 1/5 = 0.2.
  4. Compare to continuous uniform where P(X = 3) would be 0.

Answer. Discrete; P(X = 3) = 0.2.

Common mistakes
  • Asking for P(X = c) on a continuous variable and expecting a positive number; it is always 0.
  • Treating a heavily rounded continuous measurement as truly discrete; the underlying quantity is still continuous.
  • Summing a density or integrating a mass function. Discrete uses sums of the PMF; continuous uses integrals of the PDF.
✎ Try it yourself

Problem. Classify each and name the right function (PMF or PDF): (a) the number of heads in 10 flips, (b) a person's reaction time in seconds.

Solution. (a) Counting outcome, discrete, described by a PMF. (b) Measured on a continuum, continuous, described by a PDF.

Probability mass functions (PMF)

A PMF is the full probability table of a discrete variable. This lesson shows how to read, validate, and use it.

The probability mass function of a discrete random variable X is p(x) = P(X = x). A valid PMF has two properties: every value is non-negative, p(x) >= 0, and all values sum to 1 over the support. From the PMF you get the probability of any event by adding the masses of the values in it: P(X in A) = sum over x in A of p(x). The PMF is the complete description of a discrete variable — every expectation, variance, and CDF derives from it. In data science, an estimated PMF is just a normalized histogram of categorical or count data, and many models (naive Bayes, language models) store and manipulate PMFs directly. The core skills are validating that a candidate table is a legitimate PMF and summing the right entries to answer a question.

Worked Example 1

Problem. X has p(0)=0.2, p(1)=0.5, p(2)=0.3. Verify it is a valid PMF and find P(X >= 1).

  1. Non-negativity: all of 0.2, 0.5, 0.3 are >= 0.
  2. Sum: 0.2 + 0.5 + 0.3 = 1.0, so it is valid.
  3. P(X >= 1) = p(1) + p(2) = 0.5 + 0.3.
  4. = 0.8.

Answer. Valid PMF; P(X >= 1) = 0.8.

Worked Example 2

Problem. A PMF is p(x) = c*x for x = 1,2,3,4. Find c.

  1. Require the masses to sum to 1: c(1+2+3+4) = 1.
  2. c * 10 = 1.
  3. c = 1/10 = 0.1.
  4. Check: p(1..4) = 0.1,0.2,0.3,0.4 sum to 1.

Answer. c = 0.1.

Worked Example 3

Problem. For the binomial(n=3, p=0.5), give the PMF and P(X = 2).

  1. p(x) = C(3,x) (0.5)^x (0.5)^(3-x) = C(3,x)/8.
  2. p(0)=1/8, p(1)=3/8, p(2)=3/8, p(3)=1/8.
  3. P(X=2) = 3/8.
  4. = 0.375; masses sum to 8/8 = 1.

Answer. P(X = 2) = 3/8 = 0.375.

Common mistakes
  • Letting the masses sum to something other than 1. Always normalize by dividing by the total.
  • Allowing a negative mass. Any p(x) < 0 disqualifies the table as a PMF.
  • Confusing p(x) = P(X = x) with a cumulative value; the PMF is the per-point probability, not P(X <= x).
✎ Try it yourself

Problem. X takes values 1,2,3 with p(1)=0.5, p(2)=k, p(3)=0.2. Find k and P(X <= 2).

Solution. Sum to 1: 0.5 + k + 0.2 = 1, so k = 0.3. P(X <= 2) = p(1) + p(2) = 0.5 + 0.3 = 0.8.

Probability density functions (PDF)

For continuous variables, probability comes from area, not point values. This lesson explains the density function and how to integrate it.

A continuous random variable is described by a probability density function f(x), a non-negative curve whose total area equals 1. Unlike a PMF, f(x) is not a probability — it can exceed 1 — it is a density, and probability comes from area: P(a <= X <= b) = integral from a to b of f(x) dx. Because a single point has no width, P(X = c) = 0, so for continuous variables the inequalities <= and < give the same probability. The height f(x) tells you relative likelihood: where the density is larger, values cluster more. In data science, densities underlie kernel density estimation, likelihoods in maximum-likelihood fitting, and the smooth curves we overlay on histograms. The essential skill is integrating the density (analytically or numerically) over the interval of interest.

Worked Example 1

Problem. X has density f(x) = 2x on [0,1]. Verify it integrates to 1 and find P(X <= 0.5).

  1. Integral of 2x from 0 to 1 = [x^2] from 0 to 1 = 1, so it is a valid density.
  2. P(X <= 0.5) = integral of 2x from 0 to 0.5 = [x^2] from 0 to 0.5.
  3. = 0.25 - 0 = 0.25.

Answer. Valid density; P(X <= 0.5) = 0.25.

Worked Example 2

Problem. For the uniform density on [0,4], find P(1 <= X <= 3).

  1. Uniform density is constant f(x) = 1/(4-0) = 0.25 on [0,4].
  2. P(1 <= X <= 3) = (length 2) * 0.25.
  3. = 0.5.
  4. Endpoints do not matter since point probabilities are 0.

Answer. P(1 <= X <= 3) = 0.5.

Worked Example 3

Problem. Explain why a density value f(2) = 1.5 is allowed, then for f(x)=2x on [0,1] state P(X = 0.5).

  1. A density is probability per unit length, so its height can exceed 1 as long as total area is 1.
  2. Here f(0.5) = 2(0.5) = 1.0; densities like 1.5 elsewhere would be fine.
  3. P(X = 0.5) is the area over a zero-width point.
  4. = 0.

Answer. Densities can exceed 1; P(X = 0.5) = 0.

Common mistakes
  • Reading f(x) as a probability. It is a density; only its integral over an interval is a probability.
  • Worrying that f(x) > 1 is invalid. Heights can exceed 1; only the total area must equal 1.
  • Distinguishing < from <= for continuous variables. They give identical probabilities because points carry zero probability.
✎ Try it yourself

Problem. X has density f(x) = 3x^2 on [0,1]. Find P(X <= 0.5).

Solution. Integral of 3x^2 from 0 to 0.5 = [x^3] from 0 to 0.5 = 0.125. So P(X <= 0.5) = 0.125.

Cumulative distribution functions (CDF)

The CDF is one function that works for any random variable, discrete or continuous. This lesson defines it and shows how to extract probabilities.

The cumulative distribution function is F(x) = P(X <= x). It is defined for every random variable, which makes it the universal description of a distribution. A CDF is non-decreasing, approaches 0 as x goes to minus infinity and 1 as x goes to plus infinity, and is right-continuous. For a discrete variable F is a step function that jumps by p(x) at each value; for a continuous variable F is smooth and its derivative is the density. From the CDF you compute interval probabilities by subtraction: P(a < X <= b) = F(b) - F(a). The inverse of the CDF gives quantiles, which underlie percentiles, the inverse-transform sampling method, and confidence intervals. In data science the empirical CDF — the fraction of data at most x — is a fundamental nonparametric summary of a sample.

Worked Example 1

Problem. X is uniform on [0,10]. Find F(3) and P(2 < X <= 6).

  1. For uniform [0,10], F(x) = x/10 on that range.
  2. F(3) = 3/10 = 0.3.
  3. P(2 < X <= 6) = F(6) - F(2) = 0.6 - 0.2.
  4. = 0.4.

Answer. F(3) = 0.3; P(2 < X <= 6) = 0.4.

Worked Example 2

Problem. A discrete X has p(0)=0.2, p(1)=0.5, p(2)=0.3. Give F(x) at x = 0, 1, 2 and find P(X <= 1).

  1. F(0) = p(0) = 0.2.
  2. F(1) = p(0)+p(1) = 0.7.
  3. F(2) = 0.2+0.5+0.3 = 1.0.
  4. P(X <= 1) = F(1) = 0.7 (the CDF jumps by 0.5 at x=1).

Answer. F(0)=0.2, F(1)=0.7, F(2)=1.0; P(X <= 1) = 0.7.

Worked Example 3

Problem. For a standard normal, use the CDF to find P(-1 < Z <= 1).

  1. P(-1 < Z <= 1) = F(1) - F(-1).
  2. Standard normal CDF: F(1) ≈ 0.8413, F(-1) ≈ 0.1587.
  3. Difference = 0.8413 - 0.1587.
  4. = 0.6826, matching the ~68% rule.

Answer. P(-1 < Z <= 1) ≈ 0.6826.

Common mistakes
  • Expecting a CDF to decrease somewhere. It is always non-decreasing; a dip signals an arithmetic error.
  • Mishandling discrete endpoints. P(X <= 1) includes the jump at 1, while P(X < 1) excludes it.
  • Forgetting F(b) - F(a) computes P(a < X <= b), not P(a <= X <= b), which matters for discrete variables.
✎ Try it yourself

Problem. For an exponential variable with rate 1, F(x) = 1 - e^(-x). Find P(X <= 2).

Solution. F(2) = 1 - e^(-2) = 1 - 0.1353 = 0.8647. So P(X <= 2) ≈ 0.865.

Functions and transformations of random variables

Applying a function to a random variable creates a new one with its own distribution. This lesson shows how transformations reshape distributions.

If X is a random variable and g is a function, then Y = g(X) is a new random variable whose distribution is induced by X's. For a discrete X, the PMF of Y collects the masses of all x mapping to each y. For a continuous, monotonic g, the change-of-variables formula gives the density of Y as f_X(x) / |g'(x)|, evaluated at x = g^{-1}(y); the derivative factor accounts for how g stretches or compresses the scale. Linear transformations Y = aX + b shift and rescale without changing shape, which is exactly how standardization (z = (X - mu)/sigma) and de-standardization work. In data science, transformations such as log, square root, and Box-Cox are used to stabilize variance or make skewed data more normal; understanding how they change the distribution is essential to interpreting the results.

Worked Example 1

Problem. X is uniform on {1,2,3} and Y = X^2. Find the PMF of Y.

  1. Each x has probability 1/3.
  2. Y values: 1->1, 2->4, 3->9, all distinct.
  3. So P(Y=1)=P(Y=4)=P(Y=9)=1/3.
  4. The transformation relabels values but keeps the equal masses.

Answer. Y in {1,4,9}, each with probability 1/3.

Worked Example 2

Problem. X ~ Normal(mu=10, sigma=2). Describe the distribution of Y = (X - 10)/2.

  1. Linear transform Y = aX + b with a = 1/2, b = -5.
  2. Mean: E[Y] = (E[X]-10)/2 = (10-10)/2 = 0.
  3. SD: SD(Y) = |a| sigma = (1/2)(2) = 1.
  4. So Y is standard normal, Normal(0,1).

Answer. Y ~ Normal(0, 1), the standard normal.

Worked Example 3

Problem. X is uniform on [0,1] and Y = -ln(X). Find the density of Y.

  1. The CDF: P(Y <= y) = P(-ln X <= y) = P(X >= e^{-y}) = 1 - e^{-y} for y >= 0.
  2. Differentiate to get the density f_Y(y) = e^{-y}.
  3. This is the exponential distribution with rate 1.
  4. Thus transforming a uniform by -ln yields an Exponential(1).

Answer. Y ~ Exponential(rate 1), density e^{-y} for y >= 0.

Common mistakes
  • Forgetting the Jacobian |g'(x)| in the continuous change-of-variables formula; without it the new density will not integrate to 1.
  • Applying the monotonic-transform formula to a non-monotonic g (like X^2 over symmetric ranges) without summing all preimages.
  • Assuming E[g(X)] = g(E[X]). This holds only for linear g; for nonlinear g use LOTUS instead.
✎ Try it yourself

Problem. X is uniform on [0,1]. Find the density of Y = 2X + 1 and its range.

Solution. As X ranges over [0,1], Y ranges over [1,3]. Since Y = 2X+1 is linear with slope 2, f_Y(y) = f_X(x)/|2| = 1/2 on [1,3]. So Y is uniform on [1,3].

Key terms
  • Random variable — a function assigning a numeric value to each outcome in the sample space.
  • Discrete random variable — one taking countably many values, described by a probability mass function.
  • Continuous random variable — one taking values in an interval, described by a probability density function.
  • Probability mass function (PMF) — gives P(X = x) for a discrete variable; values are non-negative and sum to 1.
  • Probability density function (PDF) — a non-negative curve whose area over an interval gives the probability for a continuous variable.
  • Cumulative distribution function (CDF) — F(x) = P(X <= x), defined for any random variable and always non-decreasing.
  • Support — the set of values a random variable can actually take with non-zero probability or density.
  • Transformation — a new variable Y = g(X) whose distribution is derived from X's distribution.
Assignment · Build a CDF from samples

Pick one discrete and one continuous random variable. In Python or R, draw many samples from each, then construct an empirical CDF and overlay it on the theoretical CDF. For the continuous case, also estimate the PDF with a histogram or kernel density and compare it to the true density. Comment on how sample size affects the match.

Deliverable · A script and two figures (empirical vs. theoretical CDF, histogram vs. PDF) with a short note on convergence as sample size grows.

Quiz · 5 questions
  1. 1. For a continuous random variable, what is P(X = c) for a single point c?

  2. 2. Which property must every CDF satisfy?

  3. 3. A valid PMF for a discrete variable must have probabilities that:

  4. 4. How do you get a probability over an interval from a PDF?

  5. 5. A random variable is best described as:

You'll be able to

I can map experiment outcomes to a random variable and choose between discrete and continuous models.

I can read and use PMFs, PDFs, and CDFs to compute probabilities.

I can describe how a transformation changes a random variable's distribution.

Weeks 7-8 Unit 4: Discrete Distributions
model-bernoulliapply-binomialapply-geometricapply-poissonapply-hypergeometricselect-discrete-model
Lecture
Bernoulli and indicator variables

Every yes/no event has a one-trial random variable behind it. This lesson introduces the Bernoulli distribution and the indicator trick.

A Bernoulli random variable models a single trial with two outcomes: it equals 1 (success) with probability p and 0 (failure) with probability 1 - p. Its mean is E[X] = p and its variance is Var(X) = p(1 - p), which is largest at p = 0.5. The indicator variable I_A equals 1 when event A occurs and 0 otherwise, so it is a Bernoulli with p = P(A); crucially E[I_A] = P(A), turning probabilities into expectations. Indicators are the atom from which other distributions are built: a binomial is a sum of independent Bernoullis. In data science Bernoulli variables encode binary labels, conversion events, and clicks, and the indicator-equals-probability identity is the trick behind linearity-of-expectation proofs and Monte Carlo probability estimates.

Worked Example 1

Problem. A biased coin has P(heads) = 0.3. Let X = 1 for heads. Find E[X] and Var(X).

  1. X is Bernoulli with p = 0.3.
  2. E[X] = p = 0.3.
  3. Var(X) = p(1-p) = 0.3 * 0.7.
  4. = 0.21.

Answer. E[X] = 0.3, Var(X) = 0.21.

Worked Example 2

Problem. Roll a die. Let I = 1 if the roll is a 6. Show E[I] = P(roll = 6).

  1. I is an indicator for the event 'roll = 6'.
  2. P(roll = 6) = 1/6.
  3. E[I] = 1*P(I=1) + 0*P(I=0) = P(I=1) = 1/6.
  4. So the expectation of the indicator equals the event's probability.

Answer. E[I] = 1/6 = P(roll = 6).

Worked Example 3

Problem. For which p is a Bernoulli's variance maximized, and what is that maximum?

  1. Var = p(1-p) = p - p^2.
  2. Differentiate: d/dp (p - p^2) = 1 - 2p = 0, so p = 0.5.
  3. Var at p=0.5 = 0.5 * 0.5 = 0.25.
  4. Variance (uncertainty) peaks for a fair 50/50 trial.

Answer. Maximized at p = 0.5 with variance 0.25.

Common mistakes
  • Writing the variance as p instead of p(1-p). The mean is p; the variance is p(1-p).
  • Forgetting the indicator identity E[I_A] = P(A), which is the bridge from probabilities to expectations.
  • Coding success/failure as something other than 1/0, which breaks the mean-equals-p convenience.
✎ Try it yourself

Problem. A free-throw shooter makes 80% of shots. Let X = 1 for a make. Find E[X] and Var(X).

Solution. X ~ Bernoulli(0.8). E[X] = 0.8. Var(X) = 0.8 * 0.2 = 0.16.

The binomial distribution

Count the successes in a fixed number of independent trials and you get the binomial. This lesson develops its PMF and moments.

The binomial distribution counts the number of successes X in n independent Bernoulli trials each with success probability p. Its PMF is P(X = k) = C(n,k) p^k (1-p)^{n-k}, where C(n,k) counts which k of the n trials succeed, and the powers give the probability of any specific such arrangement. The mean is E[X] = np and the variance is Var(X) = np(1-p), both following from viewing X as a sum of n independent Bernoullis. The four binomial assumptions are: fixed n, independent trials, constant p, and two outcomes per trial. In data science the binomial models conversions out of n visitors, defective items per batch, and the numerator of an estimated proportion; it is the backbone of proportion tests and A/B testing math.

Worked Example 1

Problem. Flip a fair coin 5 times. Find P(exactly 3 heads).

  1. X ~ Binomial(n=5, p=0.5).
  2. P(X=3) = C(5,3) (0.5)^3 (0.5)^2 = 10 * (0.5)^5.
  3. = 10/32.
  4. = 0.3125.

Answer. P(3 heads) = 10/32 = 0.3125.

Worked Example 2

Problem. A factory's parts are defective with p = 0.1. In a batch of 20, find the expected number of defects and the variance.

  1. X ~ Binomial(20, 0.1).
  2. E[X] = np = 20 * 0.1 = 2.
  3. Var(X) = np(1-p) = 20 * 0.1 * 0.9.
  4. = 1.8.

Answer. E[X] = 2 defects, Var(X) = 1.8.

Worked Example 3

Problem. A quiz has 4 multiple-choice questions, each with 4 options answered by guessing (p=0.25). Find P(at least 1 correct).

  1. X ~ Binomial(4, 0.25). Use the complement.
  2. P(X = 0) = C(4,0)(0.25)^0(0.75)^4 = (0.75)^4.
  3. = 0.3164.
  4. P(X >= 1) = 1 - 0.3164 = 0.6836.

Answer. P(at least 1 correct) ≈ 0.684.

Common mistakes
  • Using the binomial when trials are dependent (sampling without replacement) — that is the hypergeometric setting.
  • Forgetting the C(n,k) coefficient and computing only p^k(1-p)^{n-k}, which is the probability of one specific ordering.
  • Confusing 'exactly k' with 'at least k'; the latter needs a sum of PMF terms or a complement.
✎ Try it yourself

Problem. A basketball player makes 70% of free throws. Out of 10 attempts, find P(exactly 8 made).

Solution. X ~ Binomial(10, 0.7). P(X=8) = C(10,8)(0.7)^8(0.3)^2 = 45 * 0.05765 * 0.09 ≈ 0.2335.

The geometric distribution

How many tries until the first success? The geometric distribution answers that, with a famous memoryless twist.

The geometric distribution models the number of independent Bernoulli trials X until (and including) the first success, where each trial succeeds with probability p. Its PMF is P(X = k) = (1-p)^{k-1} p for k = 1, 2, 3, ...: k-1 failures followed by a success. The mean is E[X] = 1/p and the variance is (1-p)/p^2. Its defining feature is memorylessness: given that the first k trials all failed, the distribution of additional trials needed is the same as from the start, P(X > m + n | X > m) = P(X > n). In data science the geometric models the number of attempts until an event (a click, a conversion, a system failure) and appears in retry logic, churn timing, and as the discrete analogue of the exponential distribution.

Worked Example 1

Problem. Roll a die until the first 6. Find P(first 6 on the 3rd roll) and the expected number of rolls.

  1. p = 1/6, so X ~ Geometric(1/6).
  2. P(X=3) = (5/6)^2 (1/6) = (25/36)(1/6).
  3. = 25/216 ≈ 0.1157.
  4. E[X] = 1/p = 6 rolls.

Answer. P(X=3) ≈ 0.116; expected 6 rolls.

Worked Example 2

Problem. A sales rep closes 20% of calls. Find P(first sale within the first 3 calls).

  1. p = 0.2. P(X <= 3) = 1 - P(no sale in 3 calls).
  2. P(no sale in 3) = (0.8)^3 = 0.512.
  3. P(X <= 3) = 1 - 0.512.
  4. = 0.488.

Answer. P(first sale by call 3) = 0.488.

Worked Example 3

Problem. A machine fails on any day with p = 0.05. Given it has run 10 days without failure, what is P(it runs at least 5 more days)?

  1. Geometric is memoryless, so past survival does not matter.
  2. P(at least 5 more failure-free days) = P(no failure in 5 days) = (0.95)^5.
  3. = 0.7738.
  4. Same as if the machine were brand new.

Answer. ≈ 0.774, independent of the 10 days already survived.

Common mistakes
  • Mixing the two conventions: 'trials until first success' (support 1,2,...) vs 'failures before first success' (support 0,1,...). SciPy uses the former; numpy.random.geometric the former too, but be careful.
  • Forgetting memorylessness and 'adjusting' the probability after a run of failures; it does not change.
  • Writing the mean as p rather than 1/p; rarer successes mean more expected trials.
✎ Try it yourself

Problem. A gachapon machine gives a rare prize with probability 0.1 per try. What is the expected number of tries to get it, and P(getting it on exactly the 2nd try)?

Solution. X ~ Geometric(0.1). E[X] = 1/0.1 = 10 tries. P(X=2) = (0.9)^1 (0.1) = 0.09.

The Poisson distribution

When rare events arrive at a steady average rate, counts follow the Poisson distribution. This lesson develops it and its rate parameter.

The Poisson distribution models the number of events occurring in a fixed interval of time or space when events happen independently at a constant average rate lambda. Its PMF is P(X = k) = e^{-lambda} lambda^k / k! for k = 0, 1, 2, .... A distinctive property is that the mean and variance are both equal to lambda, which provides a quick diagnostic check on count data. The Poisson arises as the limit of a binomial when n is large and p is small with np = lambda fixed, so it approximates rare-event counts. In data science the Poisson models website hits per minute, defects per unit, support tickets per day, and is the basis of Poisson regression for count outcomes. The key skill is identifying lambda for the relevant interval and scaling it when the interval length changes.

Worked Example 1

Problem. A call center receives 3 calls per minute on average. Find P(exactly 5 calls in a minute).

  1. X ~ Poisson(lambda = 3).
  2. P(X=5) = e^{-3} 3^5 / 5! = e^{-3} * 243 / 120.
  3. = 0.0498 * 2.025.
  4. ≈ 0.1008.

Answer. P(5 calls) ≈ 0.101.

Worked Example 2

Problem. Same center (3/min). Find P(no calls in a 2-minute window).

  1. Scale the rate: over 2 minutes lambda = 3 * 2 = 6.
  2. P(X=0) = e^{-6} 6^0 / 0! = e^{-6}.
  3. = 0.00248.
  4. Long quiet windows are very unlikely at this rate.

Answer. P(0 in 2 min) = e^{-6} ≈ 0.00248.

Worked Example 3

Problem. Defects occur at 0.5 per meter of cable. Find P(at least 1 defect in a 4-meter cable).

  1. Over 4 meters lambda = 0.5 * 4 = 2.
  2. Use the complement: P(X >= 1) = 1 - P(X=0).
  3. P(X=0) = e^{-2} = 0.1353.
  4. P(X >= 1) = 1 - 0.1353 = 0.8647.

Answer. P(at least 1 defect) ≈ 0.865.

Common mistakes
  • Failing to rescale lambda to the interval of interest. Rates are per-unit; multiply by the interval length.
  • Using Poisson when the mean and variance of the data differ greatly (overdispersion); a different model may fit better.
  • Treating lambda as a probability. It is an expected count and can exceed 1.
✎ Try it yourself

Problem. Emails arrive at an average of 4 per hour. Find P(exactly 2 emails in the next 30 minutes).

Solution. For 30 minutes lambda = 4 * 0.5 = 2. P(X=2) = e^{-2} 2^2 / 2! = 0.1353 * 4 / 2 = 0.2707.

The discrete uniform and hypergeometric distributions

Two more workhorses: equal-chance values and sampling without replacement. This lesson covers the discrete uniform and hypergeometric.

The discrete uniform distribution assigns equal probability 1/n to each of n values, such as the faces of a fair die; its mean is the midpoint of the range. The hypergeometric distribution models the number of successes when drawing n items without replacement from a finite population of N items containing K successes. Its PMF is P(X = k) = C(K,k) C(N-K, n-k) / C(N, n). Because draws are without replacement, trials are dependent and the success probability shifts after each draw, distinguishing it from the binomial. When the population is large relative to the sample, the hypergeometric is well approximated by a binomial. In data science the hypergeometric underlies the math of card and lottery problems, defect sampling from finite lots, and Fisher's exact test for 2x2 contingency tables.

Worked Example 1

Problem. A fair die shows values 1-6. State the distribution and find the mean.

  1. Each value 1..6 has probability 1/6: discrete uniform.
  2. Mean = (1+2+3+4+5+6)/6 = 21/6.
  3. = 3.5.
  4. Variance = ((6^2 - 1)/12) = 35/12 ≈ 2.917.

Answer. Discrete uniform; mean 3.5.

Worked Example 2

Problem. From a deck of 52 (4 aces), draw 5 cards. Find P(exactly 2 aces).

  1. N=52, K=4 aces, n=5, want k=2: hypergeometric.
  2. P = C(4,2) C(48,3) / C(52,5) = 6 * 17296 / 2598960.
  3. = 103776 / 2598960.
  4. ≈ 0.0399.

Answer. P(exactly 2 aces) ≈ 0.0399.

Worked Example 3

Problem. A box has 10 items, 3 defective. Draw 4 without replacement. Find P(no defectives).

  1. N=10, K=3 defective, n=4, want k=0 defective.
  2. P(X=0) = C(3,0) C(7,4) / C(10,4) = 1 * 35 / 210.
  3. = 35/210.
  4. = 1/6 ≈ 0.1667.

Answer. P(no defectives) = 1/6 ≈ 0.167.

Common mistakes
  • Using the binomial for without-replacement sampling from a small population; the hypergeometric is correct because trials are dependent.
  • Mislabeling N, K, n, and k. N is the population, K its successes, n the draw size, k the observed successes.
  • Forgetting that for a large population the hypergeometric and binomial nearly coincide, so either is fine only when N >> n.
✎ Try it yourself

Problem. A lottery has 49 numbers; 6 are winners. You pick 6. Find P(matching exactly 3 winners).

Solution. N=49, K=6, n=6, k=3. P = C(6,3) C(43,3) / C(49,6) = 20 * 12341 / 13983816 = 246820/13983816 ≈ 0.0177.

Choosing a discrete model for real data

Knowing the distributions is half the battle; matching one to a scenario is the skill. This lesson gives a decision framework.

Selecting a discrete model starts with the question being asked. Ask: Is it a single yes/no trial? Bernoulli. A count of successes in a fixed number of independent trials with constant p? Binomial. The number of trials until the first success? Geometric. A count of events in a fixed interval at a steady rate, with no fixed n? Poisson. Successes drawn without replacement from a finite population? Hypergeometric. Equal chances among finitely many values? Discrete uniform. Two practical checks help: compare the sample mean and variance (equal suggests Poisson; variance < mean over n suggests binomial), and verify the independence and constant-rate assumptions. In data science this choice determines the likelihood used for fitting, so a mismatch biases parameter estimates and downstream predictions. When in doubt, fit candidates, simulate from each, and compare to the data.

Worked Example 1

Problem. Out of 200 website visitors, 18 signed up. Which model fits the count of sign-ups, and what is the estimated parameter?

  1. Fixed number of independent visitors, each signs up or not: binomial.
  2. n = 200, estimate p = 18/200.
  3. p_hat = 0.09.
  4. Model: Binomial(200, 0.09).

Answer. Binomial(n=200, p≈0.09).

Worked Example 2

Problem. A server logs the number of errors each hour over many hours; the mean is 2.0 and the variance is 2.1. Which model is suggested?

  1. Counts of events per fixed interval with no upper bound: candidate Poisson.
  2. Poisson check: mean ≈ variance.
  3. Here 2.0 ≈ 2.1, consistent with Poisson.
  4. Adopt Poisson(lambda ≈ 2).

Answer. Poisson with lambda ≈ 2 (mean ≈ variance).

Worked Example 3

Problem. You record how many calls a sales rep makes before the first sale, repeated over many days. Which model?

  1. The variable is the number of trials until the first success.
  2. Trials are independent with roughly constant success probability p.
  3. This is the geometric distribution.
  4. Estimate p as 1 / (average number of calls to first sale).

Answer. Geometric, with p ≈ 1/mean(calls-to-first-sale).

Common mistakes
  • Defaulting to Poisson for any count without checking mean ≈ variance; overdispersed data violate it.
  • Using a binomial when there is no fixed number of trials n; an open-ended count points to Poisson or geometric.
  • Ignoring dependence from without-replacement sampling, which calls for the hypergeometric rather than the binomial.
✎ Try it yourself

Problem. A quality inspector draws 5 widgets without replacement from a crate of 50 (which contains 8 defectives) and counts defectives. Which distribution and parameters?

Solution. Without-replacement draws from a finite population make this hypergeometric: N=50, K=8 defectives, n=5 draws. So X ~ Hypergeometric(N=50, K=8, n=5).

Key terms
  • Bernoulli distribution — a single trial with success probability p, taking value 1 with probability p and 0 otherwise.
  • Binomial distribution — the number of successes in n independent Bernoulli trials with the same p.
  • Geometric distribution — the number of trials until the first success in repeated Bernoulli trials.
  • Poisson distribution — counts of events in a fixed interval when events occur independently at a constant average rate lambda.
  • Discrete uniform distribution — every value in a finite set is equally likely.
  • Hypergeometric distribution — successes drawn without replacement from a finite population.
  • Rate parameter (lambda) — the expected number of Poisson events per interval, equal to both its mean and variance.
  • Memorylessness — the geometric property that past failures do not change the chance of future success.
Assignment · Fit a distribution to count data

Choose a real or synthetic count dataset (for example, emails per hour or defects per batch). In Python (SciPy) or R, plot a histogram, then fit and overlay both a binomial and a Poisson model. Use simulation to draw samples from your chosen model and compare to the data. Argue which model fits better and why, referencing the mean-equals-variance check for Poisson.

Deliverable · A script with an annotated figure and a short justification of the chosen distribution and its estimated parameters.

Quiz · 5 questions
  1. 1. You flip a fair coin 10 times. The number of heads follows which distribution?

  2. 2. For a Poisson distribution with rate lambda, the mean and variance are:

  3. 3. Which scenario is best modeled by a geometric distribution?

  4. 4. When should you use the hypergeometric instead of the binomial?

  5. 5. A Bernoulli random variable can take which values?

You'll be able to

I can identify which discrete distribution fits a counting or trial-based scenario.

I can compute probabilities and parameters for binomial, geometric, and Poisson models.

I can use SciPy or R to evaluate PMFs, CDFs, and simulate discrete data.

Weeks 9-10 Unit 5: Continuous Distributions
apply-uniformapply-exponentialapply-normalcompute-zscorerecognize-gamma-betacompute-quantiles
Lecture
The continuous uniform distribution

The simplest continuous model spreads probability evenly over an interval. This lesson covers the continuous uniform distribution.

The continuous uniform distribution on [a, b] has a constant density f(x) = 1/(b - a) for a <= x <= b and 0 elsewhere, so every equal-length sub-interval is equally likely. Its CDF rises linearly: F(x) = (x - a)/(b - a) on the interval. The mean is the midpoint (a + b)/2 and the variance is (b - a)^2 / 12. Probabilities are just ratios of lengths: P(c <= X <= d) = (d - c)/(b - a). The standard uniform on [0, 1] is especially important because it is the raw material of random number generation: applying the inverse CDF of any distribution to a Uniform(0,1) draw produces a sample from that distribution (inverse-transform sampling). In data science the uniform models 'no preference' priors, randomization in experiments, and is the seed for simulating every other distribution.

Worked Example 1

Problem. X is uniform on [0, 20]. Find P(X <= 5) and the mean.

  1. Density is constant 1/20.
  2. P(X <= 5) = 5/20 = 0.25.
  3. Mean = (0 + 20)/2.
  4. = 10.

Answer. P(X <= 5) = 0.25; mean = 10.

Worked Example 2

Problem. A bus arrives uniformly between minutes 0 and 30 after you arrive. Find P(you wait between 10 and 20 minutes).

  1. X ~ Uniform(0, 30), density 1/30.
  2. P(10 <= X <= 20) = (20 - 10)/30.
  3. = 10/30.
  4. = 1/3 ≈ 0.333.

Answer. P(10 to 20 min) = 1/3 ≈ 0.333.

Worked Example 3

Problem. X is uniform on [2, 8]. Find its variance.

  1. Variance of Uniform(a,b) = (b - a)^2 / 12.
  2. b - a = 8 - 2 = 6.
  3. Var = 6^2 / 12 = 36/12.
  4. = 3.

Answer. Var(X) = 3.

Common mistakes
  • Forgetting to normalize the density to 1/(b-a); using height 1 makes the area exceed 1 unless b-a=1.
  • Computing the variance as (b-a)^2 instead of dividing by 12.
  • Using the discrete-uniform formula (counting values) for a continuous interval; here probability is length-based.
✎ Try it yourself

Problem. A random number generator returns X uniform on [0, 1]. Find P(0.2 <= X <= 0.7) and the mean.

Solution. Density is 1 on [0,1]. P(0.2 <= X <= 0.7) = 0.7 - 0.2 = 0.5. Mean = (0+1)/2 = 0.5.

The exponential distribution and waiting times

How long until the next event? The exponential distribution models waiting times in a steady stream of events.

The exponential distribution models the waiting time until the next event in a Poisson process with rate lambda. Its density is f(x) = lambda e^{-lambda x} for x >= 0, and its CDF is F(x) = 1 - e^{-lambda x}. The mean waiting time is 1/lambda and the variance is 1/lambda^2. Like the geometric, the exponential is memoryless: P(X > s + t | X > s) = P(X > t), so a component that has already lasted s hours has the same remaining-life distribution as a new one. The exponential is the continuous counterpart of the geometric and is tightly linked to the Poisson: if events arrive Poisson with rate lambda, the gaps between them are Exponential(lambda). In data science it models inter-arrival times, time-to-failure, and session durations, and is the simplest survival-analysis baseline.

Worked Example 1

Problem. Customers arrive at rate 2 per hour. Find the mean wait until the next customer and P(wait > 1 hour).

  1. X ~ Exponential(lambda = 2 per hour). Mean = 1/lambda = 0.5 hours.
  2. P(X > 1) = e^{-lambda * 1} = e^{-2}.
  3. = 0.1353.
  4. So a wait over an hour happens ~13.5% of the time.

Answer. Mean 0.5 h; P(wait > 1 h) ≈ 0.135.

Worked Example 2

Problem. A bulb's lifetime is exponential with mean 1000 hours. Find P(it lasts less than 500 hours).

  1. Mean 1/lambda = 1000, so lambda = 0.001 per hour.
  2. P(X < 500) = 1 - e^{-lambda * 500} = 1 - e^{-0.5}.
  3. = 1 - 0.6065.
  4. = 0.3935.

Answer. P(X < 500) ≈ 0.393.

Worked Example 3

Problem. The bulb has already lasted 1000 hours. Find P(it lasts at least 500 more hours).

  1. Exponential is memoryless, so prior age is irrelevant.
  2. P(extra >= 500) = P(X >= 500) for a fresh bulb = e^{-0.001 * 500}.
  3. = e^{-0.5} = 0.6065.
  4. Same as a brand-new bulb lasting 500 hours.

Answer. ≈ 0.607, independent of the 1000 hours already used.

Common mistakes
  • Confusing the rate lambda with the mean. The mean is 1/lambda, not lambda.
  • Forgetting memorylessness and adjusting the survival probability for elapsed time; it stays the same.
  • Mismatching units of lambda and x; both must use the same time scale (e.g. per hour and hours).
✎ Try it yourself

Problem. Calls arrive at a help desk at 5 per hour. Find the probability the next call comes within 6 minutes.

Solution. lambda = 5 per hour; 6 min = 0.1 hour. P(X <= 0.1) = 1 - e^{-5*0.1} = 1 - e^{-0.5} = 1 - 0.6065 = 0.3935.

The normal (Gaussian) distribution

The bell curve is the most important distribution in statistics. This lesson introduces the normal and its parameters.

The normal (Gaussian) distribution is the symmetric bell-shaped density defined by its mean mu (the center) and standard deviation sigma (the spread): f(x) = (1/(sigma*sqrt(2*pi))) exp(-(x - mu)^2 / (2 sigma^2)). It is unbounded in both directions, symmetric about mu, and follows the 68-95-99.7 empirical rule: about 68%, 95%, and 99.7% of probability lies within 1, 2, and 3 standard deviations of the mean. Its prominence comes from the Central Limit Theorem, which makes sums and averages of many independent variables approximately normal regardless of their original shape. In data science the normal models measurement error, is the assumed noise in linear regression, underlies confidence intervals and z-tests, and is the default prior and likelihood in countless methods. Probabilities are read from its CDF, usually via software or z-tables.

Worked Example 1

Problem. Heights are Normal(mu=170 cm, sigma=10 cm). Find P(height between 160 and 180 cm).

  1. 160 and 180 are mu - sigma and mu + sigma.
  2. By the 68-95-99.7 rule, about 68% lies within one sigma.
  3. P(160 <= X <= 180) ≈ 0.68.
  4. More precisely, F(1) - F(-1) = 0.6827.

Answer. ≈ 0.68 (68% within one standard deviation).

Worked Example 2

Problem. Test scores are Normal(mu=500, sigma=100). Find P(score > 650).

  1. z = (650 - 500)/100 = 1.5.
  2. P(Z > 1.5) = 1 - F(1.5).
  3. F(1.5) ≈ 0.9332.
  4. P(score > 650) = 1 - 0.9332 = 0.0668.

Answer. P(score > 650) ≈ 0.0668.

Worked Example 3

Problem. For the same scores, find P(400 <= score <= 600).

  1. z-scores: (400-500)/100 = -1 and (600-500)/100 = 1.
  2. P(-1 <= Z <= 1) = F(1) - F(-1).
  3. = 0.8413 - 0.1587.
  4. = 0.6826.

Answer. P(400 to 600) ≈ 0.683.

Common mistakes
  • Confusing variance with standard deviation in the parameters; sigma is the standard deviation, sigma^2 the variance.
  • Treating the density height f(x) as a probability; only areas under the curve are probabilities.
  • Assuming all bell-shaped or symmetric data are normal; heavy tails or bounded support can break the assumption.
✎ Try it yourself

Problem. IQ scores are Normal(mu=100, sigma=15). What fraction of people score above 130?

Solution. z = (130 - 100)/15 = 2.0. P(Z > 2) = 1 - 0.9772 = 0.0228, about 2.3% (consistent with the 95% within 2 sigma rule).

Standardization and z-scores

Any normal can be converted to the standard normal by a z-score. This lesson shows standardization and why it is useful.

Standardization rescales a value to a z-score: z = (x - mu)/sigma, the number of standard deviations x lies from the mean. If X is Normal(mu, sigma), then Z = (X - mu)/sigma is the standard normal, Normal(0, 1). This lets a single table or function answer probability questions for any normal: convert to z, look up the standard normal CDF, and you are done. Z-scores also make values from different distributions comparable on a common scale and are the basis of outlier detection (|z| large) and feature scaling in machine learning. The inverse operation, x = mu + z*sigma, converts a desired percentile back to the original units. In data science standardization is a routine preprocessing step so that variables with different units contribute comparably to models and distances.

Worked Example 1

Problem. X ~ Normal(mu=50, sigma=8). Convert x = 66 to a z-score and interpret it.

  1. z = (x - mu)/sigma = (66 - 50)/8.
  2. = 16/8.
  3. = 2.0.
  4. So 66 is exactly 2 standard deviations above the mean.

Answer. z = 2.0 (two standard deviations above the mean).

Worked Example 2

Problem. Two learners: Anna scored 85 on a test with mu=78, sigma=5; Ben scored 90 on a test with mu=82, sigma=10. Who did relatively better?

  1. Anna's z = (85 - 78)/5 = 1.4.
  2. Ben's z = (90 - 82)/10 = 0.8.
  3. Compare z-scores: 1.4 > 0.8.
  4. Anna is further above her test's mean, so she did relatively better.

Answer. Anna (z=1.4) outperformed Ben (z=0.8) relatively.

Worked Example 3

Problem. Find the value at the 90th percentile of Normal(mu=100, sigma=15).

  1. The 90th percentile of the standard normal is z ≈ 1.2816.
  2. Convert back: x = mu + z*sigma = 100 + 1.2816*15.
  3. = 100 + 19.22.
  4. ≈ 119.22.

Answer. 90th percentile ≈ 119.2.

Common mistakes
  • Dividing by the variance instead of the standard deviation when computing z.
  • Forgetting that standardization only turns a normal into THE standard normal; standardizing a non-normal variable does not make it normal.
  • Confusing the z-score (a number of standard deviations) with a probability; convert via the CDF to get a probability.
✎ Try it yourself

Problem. Reaction times are Normal(mu=250 ms, sigma=40 ms). A reading of 330 ms has what z-score, and what is P(time > 330)?

Solution. z = (330 - 250)/40 = 2.0. P(Z > 2) = 1 - 0.9772 = 0.0228, about 2.3%.

Other useful densities: gamma and beta

Beyond the normal, two flexible densities cover skewed positive quantities and bounded proportions. This lesson introduces the gamma and beta.

The gamma distribution is a flexible right-skewed density on positive values with a shape parameter k (or alpha) and a scale theta; it generalizes the exponential (the case k = 1) and models the waiting time until the k-th event in a Poisson process. Its mean is k*theta. The beta distribution lives on [0, 1] with two shape parameters alpha and beta, giving densities that can be uniform, bell-shaped, U-shaped, or skewed; its mean is alpha/(alpha + beta). The beta is the natural model for probabilities and proportions and is the conjugate prior for the binomial, so a Beta prior updated with binomial data yields a Beta posterior — the workhorse of Bayesian A/B testing. In data science gamma models positive, skewed quantities (insurance claims, durations) and beta models rates, click-through probabilities, and uncertainty about a proportion.

Worked Example 1

Problem. A Gamma with shape k=2 and scale theta=3 models a waiting time. Find its mean.

  1. Gamma mean = k * theta.
  2. = 2 * 3.
  3. = 6.
  4. Variance would be k*theta^2 = 2*9 = 18 if needed.

Answer. Mean = 6.

Worked Example 2

Problem. A click-through rate has a Beta(alpha=8, beta=2) belief. Find the mean estimate of the rate.

  1. Beta mean = alpha/(alpha + beta).
  2. = 8/(8 + 2).
  3. = 8/10.
  4. = 0.8.

Answer. Mean estimated rate = 0.8.

Worked Example 3

Problem. Start with a Beta(1,1) (uniform) prior for a conversion rate. After observing 6 conversions in 10 trials, give the posterior.

  1. Beta is conjugate to the binomial: posterior = Beta(alpha + successes, beta + failures).
  2. Successes = 6, failures = 4.
  3. Posterior = Beta(1 + 6, 1 + 4) = Beta(7, 5).
  4. Posterior mean = 7/(7+5) = 7/12 ≈ 0.583.

Answer. Posterior Beta(7, 5), mean ≈ 0.583.

Common mistakes
  • Mixing up the gamma's scale theta and rate (1/theta) parameterizations; check whether software wants scale or rate.
  • Using the beta for values outside [0,1]; it only models bounded proportions.
  • Forgetting the convenient conjugacy: Beta prior + binomial data = Beta posterior, so updating is just adding successes and failures.
✎ Try it yourself

Problem. You hold a Beta(2,2) prior for a coin's heads probability and then observe 7 heads in 10 flips. What is the posterior and its mean?

Solution. Posterior = Beta(2+7, 2+3) = Beta(9, 5). Mean = 9/(9+5) = 9/14 ≈ 0.643.

Sampling and quantiles in code

Software turns distribution theory into draws and percentiles. This lesson covers sampling, the four function families, and quantiles.

Most distributions in SciPy and R expose four operations. The PDF/PMF (scipy .pdf/.pmf, R d*) gives density or mass; the CDF (.cdf, R p*) gives P(X <= x); the quantile/inverse-CDF (.ppf, R q*) maps a probability to a value (a percentile); and the random sampler (.rvs, R r*) draws samples. The quantile function is the inverse of the CDF: ppf(0.5) is the median, ppf(0.9) the 90th percentile. A key idea is inverse-transform sampling: if U is Uniform(0,1), then F^{-1}(U) is a draw from the distribution with CDF F, which is how samplers are built. An empirical quantile from a sample (numpy.quantile or R quantile) estimates these percentiles directly from data. In data science these four operations power simulation, confidence-interval endpoints, risk measures (value-at-risk is a quantile), and reproducible experiments via a fixed seed.

Worked Example 1

Problem. Find the 95th percentile of a standard normal distribution.

  1. The 95th percentile is the inverse CDF at 0.95.
  2. Standard normal ppf(0.95) ≈ 1.645.
  3. So 95% of the standard normal lies below 1.645.
  4. This is the critical value behind a one-sided 5% test.

Answer. 95th percentile ≈ 1.645.

Worked Example 2

Problem. Use inverse-transform sampling to turn a uniform draw u = 0.5 into an Exponential(rate 1) sample.

  1. Exponential CDF: F(x) = 1 - e^{-x}; invert: x = -ln(1 - u).
  2. Plug u = 0.5: x = -ln(0.5).
  3. = 0.6931.
  4. So the median of Exponential(1) is ln(2) ≈ 0.693, matching F^{-1}(0.5).

Answer. Sample x = -ln(0.5) ≈ 0.693.

Worked Example 3

Problem. Find the interquartile range (IQR) of a Normal(mu=0, sigma=1).

  1. Q1 = ppf(0.25) ≈ -0.6745; Q3 = ppf(0.75) ≈ 0.6745.
  2. IQR = Q3 - Q1.
  3. = 0.6745 - (-0.6745).
  4. = 1.349 (about 1.35 sigma).

Answer. IQR ≈ 1.349 standard deviations.

Common mistakes
  • Confusing the CDF (probability from a value) with the quantile/ppf (value from a probability); they are inverses.
  • Forgetting SciPy uses loc/scale (and exponential uses scale = 1/rate), leading to wrong parameters.
  • Not setting a random seed before .rvs/r*, which makes simulated quantiles non-reproducible.
✎ Try it yourself

Problem. For Normal(mu=100, sigma=15), find the value below which 25% of the distribution falls (the first quartile).

Solution. Q1 = ppf(0.25). Standard normal ppf(0.25) ≈ -0.6745, so x = 100 + (-0.6745)(15) ≈ 89.88. About a quarter of values fall below ~89.9.

Key terms
  • Continuous uniform distribution — every value in an interval [a, b] is equally dense.
  • Exponential distribution — models the waiting time between events in a Poisson process; it is memoryless.
  • Normal (Gaussian) distribution — the bell-shaped density defined by its mean mu and standard deviation sigma.
  • Standard normal — the normal distribution with mean 0 and standard deviation 1, written Z.
  • Z-score — (x - mu) / sigma, the number of standard deviations a value sits from the mean.
  • Quantile — the value below which a given proportion of the distribution falls; the inverse of the CDF.
  • Gamma distribution — a flexible right-skewed density generalizing the exponential, useful for waiting times.
  • Beta distribution — a density on [0, 1] often used to model probabilities and proportions.
Assignment · Normal approximation and z-scores

In Python or R, draw a large sample from a normal distribution with a chosen mean and standard deviation. Compute z-scores, then verify empirically that about 68%, 95%, and 99.7% of the data fall within 1, 2, and 3 standard deviations of the mean. Also use the CDF/quantile functions to find the value at the 90th percentile and confirm it by counting samples.

Deliverable · A script reporting the empirical 68-95-99.7 percentages, the computed 90th percentile, and a histogram with the fitted normal curve.

Quiz · 5 questions
  1. 1. Approximately what fraction of a normal distribution lies within 2 standard deviations of the mean?

  2. 2. A z-score of 2.0 means the observation is:

  3. 3. Which distribution is the natural model for the waiting time until the next event in a Poisson process?

  4. 4. For a continuous uniform distribution on [0, 10], what is P(X <= 3)?

  5. 5. Standardizing a normal variable produces a distribution with:

You'll be able to

I can identify which continuous distribution fits a measurement or waiting-time scenario.

I can standardize values and use the normal distribution to find probabilities and quantiles.

I can use SciPy or R to evaluate PDFs, CDFs, and draw continuous samples.

Weeks 11-12 Unit 6: Expectation, Variance & Covariance
compute-expectationapply-linearitycompute-varianceapply-lotuscompute-covariance-correlationinterpret-moments
Lecture
Expected value of discrete and continuous variables

The expected value is the distribution's center of mass — the long-run average. This lesson defines it for both discrete and continuous variables.

The expected value E[X] is the probability-weighted average of a random variable's values, representing its long-run mean over many repetitions. For a discrete variable, E[X] = sum over x of x * p(x); for a continuous variable, E[X] = integral of x * f(x) dx over the support. Geometrically it is the balance point of the distribution. The expectation need not be an attainable value (a die's expectation is 3.5) and, for some heavy-tailed distributions, may not exist. In data science E[X] is the theoretical target that a sample mean estimates by the Law of Large Numbers; it defines fair prices in decision-making, the baseline prediction that minimizes squared error, and the first moment used in method-of-moments estimation. Computing it correctly is the foundation for variance, covariance, and nearly every downstream summary.

Worked Example 1

Problem. A fair six-sided die is rolled. Find E[X].

  1. Each face has probability 1/6.
  2. E[X] = (1+2+3+4+5+6)/6.
  3. = 21/6.
  4. = 3.5.

Answer. E[X] = 3.5.

Worked Example 2

Problem. A game pays $10 with probability 0.2 and costs $3 otherwise. Find the expected payoff.

  1. Values: +10 with p=0.2, -3 with p=0.8.
  2. E[X] = 10(0.2) + (-3)(0.8).
  3. = 2 - 2.4.
  4. = -0.4.

Answer. Expected payoff = -$0.40 (a losing game).

Worked Example 3

Problem. X has density f(x) = 2x on [0,1]. Find E[X].

  1. E[X] = integral of x * 2x dx from 0 to 1 = integral of 2x^2.
  2. = [2x^3/3] from 0 to 1.
  3. = 2/3.
  4. ≈ 0.667.

Answer. E[X] = 2/3 ≈ 0.667.

Common mistakes
  • Averaging the possible values without weighting by their probabilities; rare large values must be down-weighted.
  • Expecting E[X] to be a value the variable can actually take; it is a balance point, like 3.5 for a die.
  • Integrating x times the CDF instead of the density; the continuous formula uses f(x), the PDF.
✎ Try it yourself

Problem. A lottery ticket wins $100 with probability 0.01 and nothing otherwise. The ticket costs $2. What is the expected net gain?

Solution. Expected winnings = 100(0.01) + 0(0.99) = 1. Net of the $2 cost: E[net] = 1 - 2 = -$1. On average you lose a dollar per ticket.

Linearity of expectation

Expectation passes through sums and constants with no strings attached. This lesson establishes its most powerful property: linearity.

Linearity of expectation says E[aX + bY + c] = a E[X] + b E[Y] + c for any constants and any random variables X and Y — and crucially, it holds whether or not X and Y are independent. This is what makes expectation so useful: hard quantities can be broken into a sum of simple indicator variables whose expectations are easy probabilities, then added. The standard trick is to write a count as a sum of indicators (X = I_1 + ... + I_n) and use E[X] = sum of E[I_i] = sum of P(A_i). In data science, linearity lets us compute expected counts (expected number of matches, collisions, or successes) without wrestling with the joint distribution, and it underlies unbiasedness arguments for estimators. The independence-free nature is the property learners most often underuse.

Worked Example 1

Problem. Roll two dice. Find the expected value of the sum.

  1. Let S = X1 + X2 with each die's E = 3.5.
  2. By linearity, E[S] = E[X1] + E[X2].
  3. = 3.5 + 3.5.
  4. = 7.

Answer. E[sum] = 7.

Worked Example 2

Problem. If E[X] = 4, find E[3X + 5].

  1. Apply linearity with a = 3, c = 5.
  2. E[3X + 5] = 3 E[X] + 5.
  3. = 3(4) + 5.
  4. = 17.

Answer. E[3X + 5] = 17.

Worked Example 3

Problem. In a class of 30 learners with random birthdays, find the expected number of learners born on a Monday (1/7 chance each).

  1. Let I_i = 1 if learner i is born on Monday; X = sum of I_i.
  2. E[I_i] = P(Monday) = 1/7.
  3. By linearity E[X] = 30 * (1/7).
  4. = 30/7 ≈ 4.29 (the indicators are independent here, but linearity would hold regardless).

Answer. Expected Monday births ≈ 4.29.

Common mistakes
  • Believing linearity needs independence; it never does. Only variance of a sum requires independence (or known covariance).
  • Writing E[XY] = E[X]E[Y] under linearity; that product rule needs independence and is not part of linearity.
  • Forgetting that a constant's expectation is itself: E[c] = c, and constants factor out as E[aX] = aE[X].
✎ Try it yourself

Problem. A fair coin is flipped 100 times. Using indicators, find the expected number of heads.

Solution. Let I_i = 1 if flip i is heads, E[I_i] = 0.5. X = sum of 100 indicators, so E[X] = 100 * 0.5 = 50 heads.

Variance and standard deviation

The mean tells you the center; variance tells you the spread. This lesson defines variance and its square-root partner, the standard deviation.

Variance measures how far a random variable typically falls from its mean: Var(X) = E[(X - mu)^2], with the convenient computing form Var(X) = E[X^2] - (E[X])^2. The standard deviation sigma = sqrt(Var(X)) restores the original units, making spread interpretable. Key algebra: Var(aX + b) = a^2 Var(X) (shifts do not change spread; scaling squares), and for independent variables Var(X + Y) = Var(X) + Var(Y). Unlike expectation, variance is not linear and the additivity of variances requires independence (or adding twice the covariance otherwise). In data science variance quantifies risk and noise, drives the bias-variance tradeoff, sets confidence-interval widths through the standard error sigma/sqrt(n), and is the quantity minimized or controlled in many estimators and portfolios.

Worked Example 1

Problem. X takes values 0 and 10 each with probability 0.5. Find Var(X) and the standard deviation.

  1. E[X] = 0(0.5) + 10(0.5) = 5.
  2. E[X^2] = 0^2(0.5) + 10^2(0.5) = 50.
  3. Var = E[X^2] - (E[X])^2 = 50 - 25 = 25.
  4. SD = sqrt(25) = 5.

Answer. Var(X) = 25, SD = 5.

Worked Example 2

Problem. A fair die has Var(X) = 35/12. Find Var(2X + 3).

  1. Var(aX + b) = a^2 Var(X); the +3 does not matter.
  2. = 2^2 * 35/12.
  3. = 4 * 35/12 = 140/12.
  4. = 35/3 ≈ 11.67.

Answer. Var(2X + 3) = 35/3 ≈ 11.67.

Worked Example 3

Problem. X and Y are independent with Var(X)=4 and Var(Y)=9. Find Var(X + Y) and Var(X - Y).

  1. Independence gives Var(X + Y) = Var(X) + Var(Y) = 4 + 9 = 13.
  2. Var(X - Y) = Var(X) + (-1)^2 Var(Y) = 4 + 9.
  3. = 13 (subtraction does not reduce variance).
  4. Both sums and differences add variances when independent.

Answer. Var(X+Y) = Var(X-Y) = 13.

Common mistakes
  • Treating variance as linear; Var(aX + b) = a^2 Var(X), and the constant b drops out entirely.
  • Adding variances for X + Y when the variables are dependent; you must add 2*Cov(X,Y) as well.
  • Reporting variance when standard deviation is wanted; sigma is in the original units, variance is in squared units.
✎ Try it yourself

Problem. A Bernoulli variable has p = 0.5. Find its variance and standard deviation.

Solution. Var = p(1-p) = 0.5 * 0.5 = 0.25. SD = sqrt(0.25) = 0.5.

The law of the unconscious statistician (LOTUS)

To find the expected value of a function of X, you do not need the distribution of that function. LOTUS lets you compute it directly.

The law of the unconscious statistician (LOTUS) states that for a function g, E[g(X)] = sum over x of g(x) p(x) for discrete X, or integral of g(x) f(x) dx for continuous X. The point is that you can compute the expectation of g(X) using the distribution of X alone, without first deriving the (often messy) distribution of Y = g(X). This is how variance itself is computed: Var(X) = E[(X - mu)^2] applies LOTUS with g(x) = (x - mu)^2. A critical consequence is that for nonlinear g, E[g(X)] is generally not g(E[X]) — Jensen's inequality says E[g(X)] >= g(E[X]) for convex g. In data science LOTUS computes expected utilities, expected loss/risk, and moments, and the gap between E[g(X)] and g(E[X]) explains many averaging fallacies.

Worked Example 1

Problem. X is a fair die. Find E[X^2] using LOTUS.

  1. g(x) = x^2; weight each by 1/6.
  2. E[X^2] = (1+4+9+16+25+36)/6.
  3. = 91/6.
  4. ≈ 15.17.

Answer. E[X^2] = 91/6 ≈ 15.17.

Worked Example 2

Problem. Using the previous result, find Var(X) for a fair die via LOTUS.

  1. Var = E[X^2] - (E[X])^2.
  2. E[X^2] = 91/6, E[X] = 3.5 so (E[X])^2 = 12.25.
  3. Var = 91/6 - 12.25 = 15.1667 - 12.25.
  4. = 2.9167 = 35/12.

Answer. Var(X) = 35/12 ≈ 2.917.

Worked Example 3

Problem. X is uniform on [0,1]. Find E[e^X] and compare to e^{E[X]}.

  1. LOTUS: E[e^X] = integral of e^x * 1 dx from 0 to 1 = e - 1.
  2. = 1.7183.
  3. e^{E[X]} = e^{0.5} = 1.6487.
  4. E[e^X] > e^{E[X]}, as Jensen predicts for the convex exp.

Answer. E[e^X] = e - 1 ≈ 1.718 > e^{0.5} ≈ 1.649.

Common mistakes
  • Assuming E[g(X)] = g(E[X]); this only holds for linear g, and Jensen's inequality bounds the gap otherwise.
  • Deriving the full distribution of g(X) before taking the expectation; LOTUS avoids that extra work entirely.
  • Forgetting to weight g(x) by the distribution of X, not by a uniform weight.
✎ Try it yourself

Problem. A fair coin pays X = 1 for heads, 0 for tails. Find E[X^2] and confirm it equals Var plus mean-squared for this Bernoulli.

Solution. E[X^2] = 1^2(0.5) + 0^2(0.5) = 0.5. Since E[X] = 0.5, Var = E[X^2] - (E[X])^2 = 0.5 - 0.25 = 0.25, matching p(1-p).

Covariance and correlation

When two variables move together, covariance and correlation quantify it. This lesson defines both and explains why correlation is the standardized version.

Covariance measures how two variables vary together: Cov(X, Y) = E[(X - muX)(Y - muY)] = E[XY] - E[X]E[Y]. It is positive when the variables tend to rise together, negative when one rises as the other falls, and zero when there is no linear co-movement. But covariance is scale-dependent, so its magnitude is hard to interpret. Correlation fixes this by standardizing: rho = Cov(X, Y) / (sigmaX * sigmaY), a unit-free number in [-1, 1] where +/-1 means a perfect linear relationship and 0 means none. A crucial caveat: independence implies zero correlation, but zero correlation does not imply independence — correlation captures only linear association. In data science correlation drives feature selection, multicollinearity diagnostics, and is the building block of the covariance matrices used in PCA and portfolio optimization.

Worked Example 1

Problem. X and Y have E[X]=2, E[Y]=3, E[XY]=8. Find Cov(X,Y).

  1. Cov(X,Y) = E[XY] - E[X]E[Y].
  2. = 8 - (2)(3).
  3. = 8 - 6.
  4. = 2.

Answer. Cov(X, Y) = 2.

Worked Example 2

Problem. Continuing, if sigmaX = 1 and sigmaY = 4, find the correlation.

  1. rho = Cov/(sigmaX sigmaY).
  2. = 2 / (1 * 4).
  3. = 0.5.
  4. A moderate positive linear association.

Answer. rho = 0.5.

Worked Example 3

Problem. Let X be symmetric about 0 (e.g. uniform on {-1,0,1}) and Y = X^2. Show Cov(X,Y) = 0 despite strong dependence.

  1. By symmetry E[X] = 0 and E[XY] = E[X^3] = 0 (odd function of symmetric X).
  2. Cov = E[XY] - E[X]E[Y] = 0 - 0*E[Y].
  3. = 0.
  4. Yet Y is fully determined by X, so zero correlation does NOT mean independence.

Answer. Cov(X, Y) = 0 although X and Y are dependent.

Common mistakes
  • Reading a large covariance as a strong relationship; magnitude depends on units, so standardize to correlation first.
  • Concluding independence from zero correlation; only linear association is captured, nonlinear links can hide.
  • Forgetting Cov(X, X) = Var(X); the diagonal of a covariance matrix holds the variances.
✎ Try it yourself

Problem. Two assets have returns with Cov = 0.012, sigmaX = 0.1, sigmaY = 0.2. Find the correlation and interpret it.

Solution. rho = 0.012 / (0.1 * 0.2) = 0.012 / 0.02 = 0.6. A fairly strong positive linear relationship: the assets tend to move up and down together.

Moments and the moment-generating function (intro)

Moments summarize a distribution's shape, and one clever function encodes them all. This lesson introduces moments and the moment-generating function.

The n-th moment of X about the origin is E[X^n]; the first moment is the mean and the second central moment E[(X - mu)^2] is the variance. Higher central moments describe shape: the third (standardized) is skewness (asymmetry) and the fourth is kurtosis (tail heaviness). The moment-generating function (MGF) is M(t) = E[e^{tX}], and when it exists near 0 it 'generates' the moments: the n-th derivative of M evaluated at t = 0 equals E[X^n]. The MGF also uniquely determines a distribution and turns sums of independent variables into products of MGFs, which is one clean route to proving results like the Central Limit Theorem. In data science moments power method-of-moments estimation, skewness/kurtosis diagnostics for non-normality, and the theory behind many limit results.

Worked Example 1

Problem. A fair die has E[X] = 3.5 and E[X^2] = 91/6. State its first two moments and the variance.

  1. First moment (mean) = E[X] = 3.5.
  2. Second moment = E[X^2] = 91/6 ≈ 15.17.
  3. Variance = second moment - (first)^2 = 15.17 - 12.25.
  4. = 2.917.

Answer. Moments 3.5 and 15.17; variance 2.917.

Worked Example 2

Problem. For an Exponential(rate lambda), the MGF is M(t) = lambda/(lambda - t) for t < lambda. Use it to find E[X].

  1. E[X] = M'(0). M(t) = lambda(lambda - t)^{-1}.
  2. M'(t) = lambda(lambda - t)^{-2}.
  3. M'(0) = lambda / lambda^2.
  4. = 1/lambda, the known exponential mean.

Answer. E[X] = 1/lambda.

Worked Example 3

Problem. Using the same MGF, find E[X^2] and Var(X) for the exponential.

  1. M''(t) = 2 lambda (lambda - t)^{-3}; E[X^2] = M''(0) = 2 lambda/lambda^3 = 2/lambda^2.
  2. Var = E[X^2] - (E[X])^2 = 2/lambda^2 - 1/lambda^2.
  3. = 1/lambda^2.
  4. Matching the known exponential variance.

Answer. E[X^2] = 2/lambda^2; Var(X) = 1/lambda^2.

Common mistakes
  • Confusing raw moments E[X^n] with central moments E[(X-mu)^n]; variance is a central moment, the mean is a raw moment.
  • Forgetting that the MGF generates moments via derivatives at t = 0, not at t = 1.
  • Assuming every distribution has an MGF; heavy-tailed distributions (like the Cauchy) have none, so use the characteristic function instead.
✎ Try it yourself

Problem. The MGF of a Bernoulli(p) is M(t) = (1 - p) + p e^t. Find E[X] using M'(0).

Solution. M'(t) = p e^t, so M'(0) = p e^0 = p. Thus E[X] = p, the known Bernoulli mean.

Key terms
  • Expected value — the long-run average of a random variable, a probability-weighted sum or integral of its values.
  • Linearity of expectation — E[aX + bY] = aE[X] + bE[Y], which holds whether or not X and Y are independent.
  • Variance — E[(X - mu)^2], the expected squared deviation from the mean, measuring spread.
  • Standard deviation — the square root of the variance, expressed in the variable's own units.
  • LOTUS — the rule that E[g(X)] is computed by weighting g(x) by the distribution of X, without first finding g(X)'s distribution.
  • Covariance — E[(X - muX)(Y - muY)], measuring how two variables vary together.
  • Correlation — covariance scaled to the range [-1, 1], a unit-free measure of linear association.
  • Moment — an expected value of a power of X; the first moment is the mean and the second central moment is the variance.
Assignment · Estimate moments and correlation by simulation

In Python or R, simulate two correlated random variables (for example via a chosen covariance structure). Estimate their means, variances, covariance, and correlation from the samples and compare to the theoretical values. Then demonstrate linearity of expectation by checking that the sample mean of aX + bY matches a*mean(X) + b*mean(Y), even when X and Y are dependent.

Deliverable · A script reporting estimated vs. theoretical moments and correlation, plus a scatter plot illustrating the dependence.

Quiz · 5 questions
  1. 1. Linearity of expectation, E[X + Y] = E[X] + E[Y], requires that X and Y be:

  2. 2. For a fair six-sided die, the expected value is:

  3. 3. If Var(X) = 9, what is the standard deviation of X?

  4. 4. A correlation of -1 between X and Y indicates:

  5. 5. Covariance differs from correlation mainly because:

You'll be able to

I can compute expected value and variance for discrete and continuous random variables.

I can apply linearity of expectation even when variables are dependent.

I can compute and interpret covariance and correlation between two variables.

Weeks 13-14 Unit 7: Joint Distributions, LLN & the Central Limit Theorem
use-joint-distributionderive-marginalsanalyze-sumsapply-llnapply-cltcompute-standard-error
Lecture
Joint, marginal, and conditional distributions

Real problems involve several variables at once. This lesson sets up joint, marginal, and conditional distributions for two variables.

The joint distribution describes the probabilities of combinations of two (or more) random variables: a joint PMF p(x, y) = P(X = x, Y = y) for discrete variables, or a joint density f(x, y) for continuous ones, with the total summing or integrating to 1. From the joint you recover a marginal by summing or integrating out the other variable: p_X(x) = sum over y of p(x, y). The conditional distribution of Y given X = x renormalizes a slice of the joint: p(y | x) = p(x, y) / p_X(x). These three views — joint, marginal, conditional — are linked by p(x, y) = p(y | x) p_X(x). In data science the joint distribution is the full probabilistic model of several features, marginals describe single features, and conditionals are exactly what predictive models estimate, such as P(label | features).

Worked Example 1

Problem. A joint PMF over (X,Y) in {0,1}x{0,1}: p(0,0)=0.1, p(0,1)=0.2, p(1,0)=0.3, p(1,1)=0.4. Find the marginal of X.

  1. Sum over y for each x.
  2. p_X(0) = p(0,0)+p(0,1) = 0.1+0.2 = 0.3.
  3. p_X(1) = p(1,0)+p(1,1) = 0.3+0.4 = 0.7.
  4. Check: 0.3 + 0.7 = 1.

Answer. p_X(0) = 0.3, p_X(1) = 0.7.

Worked Example 2

Problem. Using the same joint, find the conditional P(Y = 1 | X = 1).

  1. P(Y=1 | X=1) = p(1,1)/p_X(1).
  2. = 0.4 / 0.7.
  3. ≈ 0.571.
  4. Conditioning renormalizes the X=1 row to sum to 1.

Answer. P(Y=1 | X=1) ≈ 0.571.

Worked Example 3

Problem. Are X and Y independent in this joint distribution?

  1. Independence requires p(x,y) = p_X(x) p_Y(y) for all cells.
  2. p_Y(1) = p(0,1)+p(1,1) = 0.2+0.4 = 0.6.
  3. Check cell (1,1): p_X(1)p_Y(1) = 0.7*0.6 = 0.42, but p(1,1) = 0.4.
  4. 0.42 != 0.40, so X and Y are NOT independent.

Answer. Not independent: 0.40 != 0.42.

Common mistakes
  • Forgetting to renormalize when conditioning; divide the joint by the marginal so the conditional sums to 1.
  • Summing out the wrong variable for a marginal; to get p_X you sum over y, the variable you are removing.
  • Assuming a joint factorizes; check every cell against the product of marginals before claiming independence.
✎ Try it yourself

Problem. For the joint above, find the marginal of Y and P(X = 0 | Y = 0).

Solution. p_Y(0) = p(0,0)+p(1,0) = 0.1+0.3 = 0.4. P(X=0 | Y=0) = p(0,0)/p_Y(0) = 0.1/0.4 = 0.25.

Independence of random variables

Independence of variables generalizes independence of events. This lesson states the factorization criterion and its consequences.

Two random variables X and Y are independent when their joint distribution factorizes into the product of their marginals: p(x, y) = p_X(x) p_Y(y) for all x, y (or f(x,y) = f_X(x) f_Y(y) for densities). Equivalently, the conditional distribution of one does not depend on the value of the other. Independence has powerful consequences: E[XY] = E[X]E[Y], Cov(X, Y) = 0, and Var(X + Y) = Var(X) + Var(Y). Note the one-way street: independence implies zero correlation, but zero correlation does not guarantee independence. In data science, independence (often the weaker conditional independence) is the simplifying assumption behind naive Bayes, the i.i.d. assumption justifying most estimators and the CLT, and the factorization that makes likelihoods tractable. Knowing when it holds — and the cost of assuming it wrongly — is central to sound modeling.

Worked Example 1

Problem. Two dice are rolled independently. Verify P(X=2, Y=5) factorizes.

  1. P(X=2) = 1/6, P(Y=5) = 1/6.
  2. Independent product = (1/6)(1/6) = 1/36.
  3. The joint outcome (2,5) is one of 36 equally likely pairs, so P = 1/36.
  4. Equal, so the rolls are independent.

Answer. P(X=2, Y=5) = 1/36 = P(X=2)P(Y=5).

Worked Example 2

Problem. X and Y are independent with E[X]=3, E[Y]=4, Var(X)=2, Var(Y)=5. Find E[XY] and Var(X+Y).

  1. Independence: E[XY] = E[X]E[Y] = 3*4 = 12.
  2. Var(X+Y) = Var(X) + Var(Y) (no covariance term).
  3. = 2 + 5.
  4. = 7.

Answer. E[XY] = 12; Var(X+Y) = 7.

Worked Example 3

Problem. Give a case where Cov(X,Y) = 0 but X and Y are dependent.

  1. Let X be uniform on {-1, 0, 1} and Y = X^2.
  2. E[X] = 0 and E[XY] = E[X^3] = 0, so Cov = 0.
  3. But Y is a deterministic function of X, hence dependent.
  4. Zero covariance therefore does not imply independence.

Answer. X uniform on {-1,0,1}, Y=X^2: Cov=0 yet dependent.

Common mistakes
  • Inferring independence from zero correlation; correlation only sees linear association.
  • Adding variances of a sum without checking independence; otherwise include 2*Cov(X,Y).
  • Confusing pairwise independence with mutual independence among three or more variables; all subsets must factorize.
✎ Try it yourself

Problem. X and Y are independent with Var(X) = 4, Var(Y) = 9. Find Var(2X - Y).

Solution. Var(2X - Y) = 2^2 Var(X) + (-1)^2 Var(Y) = 4*4 + 9 = 16 + 9 = 25 (no covariance term since independent).

Sums of random variables and convolution

Adding random variables combines their distributions through convolution. This lesson explains how sums behave in mean, variance, and shape.

When you add independent random variables, the means and variances simply add: E[X + Y] = E[X] + E[Y] (always) and Var(X + Y) = Var(X) + Var(Y) (when independent). The distribution of the sum, however, is the convolution of the individual distributions: P(X + Y = z) = sum over k of p_X(k) p_Y(z - k) in the discrete case, or the corresponding integral for densities. Some families are closed under addition: a sum of independent normals is normal, a sum of independent Poissons is Poisson with added rates, and a sum of n independent Bernoulli(p) is Binomial(n, p). In data science, sums and convolutions arise when aggregating independent contributions — total demand, accumulated noise, combined counts — and the closure properties let us model these aggregates exactly, while the CLT explains why many sums look normal.

Worked Example 1

Problem. X ~ Normal(2, 3) and Y ~ Normal(5, 4) are independent (means, variances). Find the distribution of X + Y.

  1. Sum of independent normals is normal.
  2. Mean = 2 + 5 = 7.
  3. Variance = 3 + 4 = 7.
  4. So X + Y ~ Normal(mean 7, variance 7).

Answer. X + Y ~ Normal(7, 7).

Worked Example 2

Problem. X ~ Poisson(3) and Y ~ Poisson(5) independent. Find the distribution of X + Y.

  1. Independent Poissons add their rates.
  2. lambda_total = 3 + 5.
  3. = 8.
  4. So X + Y ~ Poisson(8).

Answer. X + Y ~ Poisson(8).

Worked Example 3

Problem. Two independent dice X and Y. Use convolution to find P(X + Y = 4).

  1. P(sum=4) = sum over k of P(X=k)P(Y=4-k) for valid k.
  2. Pairs: (1,3),(2,2),(3,1), each with probability (1/6)(1/6)=1/36.
  3. Total = 3/36.
  4. = 1/12 ≈ 0.0833.

Answer. P(X + Y = 4) = 3/36 = 1/12.

Common mistakes
  • Adding standard deviations instead of variances; variances add (for independent variables), not SDs.
  • Assuming the sum has the same distribution shape as the parts; only special families are closed under addition.
  • Forgetting variances add only under independence; dependent sums need the covariance term.
✎ Try it yourself

Problem. X ~ Binomial(10, 0.5) and Y ~ Binomial(15, 0.5) are independent. What is the distribution of X + Y?

Solution. Independent binomials with the same p add their trial counts: X + Y ~ Binomial(10 + 15, 0.5) = Binomial(25, 0.5).

The Law of Large Numbers

Why does averaging more data help? The Law of Large Numbers guarantees the sample mean settles on the truth.

The Law of Large Numbers (LLN) states that as the sample size n grows, the sample mean of independent, identically distributed observations converges to the true expected value mu. Intuitively, random highs and lows cancel out as you average more data, so the running average stabilizes near mu. This is the formal justification for estimating an unknown mean (or any expectation, since probabilities are expectations of indicators) by simulation or by collecting data: Monte Carlo estimates work precisely because of the LLN. It is important to separate the LLN from the CLT: the LLN says where the sample mean goes (to mu), while the CLT describes the shape of its fluctuations around mu. The LLN says nothing about individual outcomes — there is no 'gambler's fallacy' correction; only the average converges.

Worked Example 1

Problem. A fair die is rolled repeatedly. What does the LLN say the running average approaches?

  1. The true mean of a fair die is E[X] = 3.5.
  2. By the LLN, the average of n rolls converges to 3.5 as n grows.
  3. Early averages fluctuate but settle near 3.5.
  4. Convergence is to the expectation, not to any particular roll value.

Answer. The running average approaches 3.5.

Worked Example 2

Problem. Explain why a Monte Carlo estimate of P(sum of two dice = 7) works.

  1. Define indicator I = 1 when the sum is 7; E[I] = P(sum=7) = 1/6.
  2. Simulate many rolls and average the indicator.
  3. By the LLN, that average converges to E[I] = 1/6 ≈ 0.1667.
  4. So the simulated fraction estimates the true probability.

Answer. The simulated fraction converges to 1/6 by the LLN.

Worked Example 3

Problem. After 10 heads in a row, is the next flip more likely to be tails (to 'balance out')?

  1. Flips are independent, so P(tails next) = 0.5 regardless of history.
  2. The LLN says the PROPORTION of heads tends to 0.5, not that short runs self-correct.
  3. The streak's effect is diluted by more flips, not reversed by them.
  4. Believing otherwise is the gambler's fallacy.

Answer. No — P(tails) stays 0.5; the LLN is about long-run proportions, not corrections.

Common mistakes
  • Confusing the LLN with the gambler's fallacy; past results do not change independent future trials.
  • Conflating LLN and CLT; the LLN gives convergence of the mean, the CLT gives its approximate normal shape.
  • Expecting fast convergence; the error of the sample mean shrinks like 1/sqrt(n), so quadrupling n only halves it.
✎ Try it yourself

Problem. You simulate flips of a fair coin and track the proportion of heads. Roughly what value does it approach as the number of flips grows very large?

Solution. The proportion of heads converges to the true probability E[I_heads] = 0.5 by the Law of Large Numbers. Individual streaks do not change this long-run limit.

The Central Limit Theorem

The most celebrated result in probability: averages of almost anything become normal. This lesson states and interprets the CLT.

The Central Limit Theorem (CLT) says that the sum (or mean) of a large number of independent, identically distributed variables is approximately normal, regardless of the original distribution's shape, provided it has finite variance. Concretely, if X1, ..., Xn have mean mu and standard deviation sigma, then the sample mean is approximately Normal(mu, sigma^2/n), and the standardized quantity (mean - mu)/(sigma/sqrt(n)) approaches the standard normal as n grows. This is why the bell curve appears everywhere: many real quantities are sums of many small independent effects. A common rule of thumb is that n around 30 gives a good approximation for moderately skewed data, though heavy skew needs larger n. In data science the CLT justifies normal-based confidence intervals, z- and t-tests, and the standard error sigma/sqrt(n) for the mean, even when the underlying data are not normal.

Worked Example 1

Problem. A population has mu = 50, sigma = 10. For samples of size n = 100, what is the approximate distribution of the sample mean?

  1. By the CLT the sample mean is approximately normal.
  2. Mean of the sample mean = mu = 50.
  3. Standard error = sigma/sqrt(n) = 10/sqrt(100) = 1.
  4. So the sample mean ~ approximately Normal(50, 1^2).

Answer. Sample mean ≈ Normal(mean 50, SD 1).

Worked Example 2

Problem. Using the above, find the approximate probability that the sample mean exceeds 52.

  1. Standardize: z = (52 - 50)/1 = 2.
  2. P(mean > 52) = P(Z > 2).
  3. = 1 - 0.9772.
  4. = 0.0228.

Answer. P(sample mean > 52) ≈ 0.0228.

Worked Example 3

Problem. Why does averaging 100 exponential waiting times look bell-shaped even though the exponential is heavily skewed?

  1. The exponential has finite mean and variance, satisfying the CLT conditions.
  2. The sample mean is a sum (over n) divided by n, so the CLT applies.
  3. As n=100 is large, the skew is averaged away and the distribution of the mean approaches normal.
  4. Its SD is the exponential SD divided by sqrt(100) = 1/10 of the original spread.

Answer. The CLT makes the mean of 100 exponentials approximately normal.

Common mistakes
  • Thinking the CLT makes the DATA normal; it is the distribution of the SAMPLE MEAN (or sum) that becomes normal.
  • Applying the CLT when the variance is infinite (e.g. Cauchy); the theorem requires a finite variance.
  • Treating n = 30 as a universal threshold; very skewed or heavy-tailed data need much larger samples.
✎ Try it yourself

Problem. Dice rolls have mu = 3.5 and sigma ≈ 1.708. For the mean of n = 50 rolls, give the approximate standard error and the distribution of the sample mean.

Solution. Standard error = sigma/sqrt(n) = 1.708/sqrt(50) ≈ 0.2415. By the CLT the sample mean is approximately Normal(3.5, 0.2415^2).

Sampling distributions and the standard error

A statistic computed from a sample is itself random. This lesson introduces sampling distributions and the standard error that measures their spread.

A sampling distribution is the distribution of a statistic (such as the sample mean or proportion) across all possible samples of a given size. Because the statistic varies from sample to sample, it has its own distribution with a center and a spread. For the sample mean, the center is the population mean mu and the spread is the standard error, SE = sigma/sqrt(n) — note this is the standard deviation of the statistic, not of the raw data. The standard error shrinks as n grows, which is why larger samples give more precise estimates, and its 1/sqrt(n) rate means quadrupling the sample size halves the error. Combined with the CLT, the sampling distribution of the mean is approximately normal, which is what makes confidence intervals (estimate +/- z*SE) and hypothesis tests work. In data science the standard error quantifies estimation uncertainty for any reported statistic.

Worked Example 1

Problem. A population has sigma = 20. Find the standard error of the mean for samples of size n = 25 and n = 100.

  1. SE = sigma/sqrt(n).
  2. n=25: SE = 20/sqrt(25) = 20/5 = 4.
  3. n=100: SE = 20/sqrt(100) = 20/10 = 2.
  4. Quadrupling n from 25 to 100 halved the SE.

Answer. SE = 4 (n=25) and SE = 2 (n=100).

Worked Example 2

Problem. A sample of 64 has mean 70 from a population with sigma = 16. Build an approximate 95% confidence interval for mu.

  1. SE = 16/sqrt(64) = 16/8 = 2.
  2. 95% interval = mean +/- 1.96 * SE = 70 +/- 1.96 * 2.
  3. = 70 +/- 3.92.
  4. = (66.08, 73.92).

Answer. Approx 95% CI for mu = (66.08, 73.92).

Worked Example 3

Problem. A poll of n = 400 finds 60% support. Find the standard error of the sample proportion.

  1. For a proportion, SE = sqrt(p(1-p)/n).
  2. = sqrt(0.6 * 0.4 / 400).
  3. = sqrt(0.24/400) = sqrt(0.0006).
  4. ≈ 0.0245 (about 2.45 percentage points).

Answer. SE of the proportion ≈ 0.0245.

Common mistakes
  • Confusing the standard error (spread of a statistic) with the standard deviation (spread of the raw data); SE = sigma/sqrt(n).
  • Forgetting the 1/sqrt(n) rate, so expecting linear precision gains; you need 4x the data to halve the error.
  • Using the data SD directly in a confidence interval instead of the standard error of the estimate.
✎ Try it yourself

Problem. A sample of n = 36 from a population with sigma = 12 has mean 50. Find the standard error and an approximate 95% confidence interval for mu.

Solution. SE = 12/sqrt(36) = 12/6 = 2. 95% CI = 50 +/- 1.96*2 = 50 +/- 3.92 = (46.08, 53.92).

Key terms
  • Joint distribution — the probabilities or density over combinations of two or more random variables.
  • Marginal distribution — the distribution of one variable obtained by summing or integrating out the others.
  • Conditional distribution — the distribution of one variable given a fixed value of another.
  • Convolution — the operation giving the distribution of a sum of independent random variables.
  • Law of Large Numbers (LLN) — as sample size grows, the sample mean converges to the true expected value.
  • Central Limit Theorem (CLT) — the sum or mean of many independent variables is approximately normal, regardless of the original distribution.
  • Sampling distribution — the distribution of a statistic (such as the sample mean) across repeated samples.
  • Standard error — the standard deviation of a sampling distribution, equal to sigma / sqrt(n) for the sample mean.
Assignment · Watch the CLT emerge

In Python or R, pick a clearly non-normal distribution (for example exponential or uniform). Repeatedly draw samples of size n, compute each sample mean, and plot the histogram of those means for several values of n (such as 1, 5, 30, 100). Overlay the normal curve predicted by the CLT and show that the standard error shrinks like sigma/sqrt(n). Also illustrate the LLN by plotting a running average converging to the true mean.

Deliverable · A script with the sequence of sample-mean histograms, a running-average plot, and a short explanation of how LLN and CLT differ.

Quiz · 5 questions
  1. 1. The Central Limit Theorem states that the distribution of the sample mean becomes approximately normal as:

  2. 2. The Law of Large Numbers says that as sample size grows, the sample mean:

  3. 3. For a sample mean from a population with standard deviation sigma, the standard error is:

  4. 4. A marginal distribution is obtained from a joint distribution by:

  5. 5. Two random variables X and Y are independent when their joint distribution:

You'll be able to

I can work with joint, marginal, and conditional distributions for two random variables.

I can explain the Law of Large Numbers and the Central Limit Theorem and when each applies.

I can demonstrate via simulation that sample means become normal as sample size grows.

Where this leads

Course milestones

Combinatorics & axioms checkpoint: model a sample space and compute event probabilities with counting and inclusion-exclusion (Units 1).
Bayesian reasoning project: solve a disease-screening problem analytically and confirm it by simulation, explaining the base-rate effect (Unit 2).
Distribution toolkit: select, fit, and simulate the right discrete and continuous distributions for given scenarios using SciPy or R (Units 3-5).
Moments & dependence lab: estimate expectation, variance, covariance, and correlation from data and verify them against theory (Unit 6).
Capstone — LLN & CLT demonstration: build a simulation that shows sample means converging and becoming normal, with shrinking standard error (Unit 7).

Free, forever. Math you can actually use.

Part of the open-source Crunch Academy tech-education path. Pair it with the data-science and ML tracks when you're ready.

All Math for Data Science courses Crunch Academy home