Knowledge Discovery
Session 02

Probability

4 hours · Week 2

Course Reader

This session covers Part 1: Core Probability and Part 2: Random Variables from the Probability for Computer Scientists course reader by Chris Piech (Stanford CS109). Also available online.

Learning Objectives

Part 1: Core Probability

Part 2: Random Variables

01 Introduction to Probability

Why Probability Matters

12 Ways Probability Thinking Prevents You From Being Fooled

Common traps in reasoning about uncertainty—and how to escape them

Equally Likely Outcomes

Sample Spaces and Events

A sample space S is the set of all possible outcomes of an experiment. An event E is any subset of the sample space.

Empirical Definition of Probability

The probability of any event E can be defined as:

P(E) = limn→∞ count(E) / n

Where count(E) is the number of times E occurred in n experiments.

Core Identities
  • 0 ≤ P(E) ≤ 1 — All probabilities are between 0 and 1
  • P(S) = 1 — All outcomes must be from the sample space
  • P(EC) = 1 − P(E) — The probability of an event from its complement

Equally Likely Formula

When every outcome in the sample space has the same probability:

Equally Likely Formula
P(E) = |E| / |S| = (number of outcomes in E) / (number of outcomes in S)
Example: Sum of Two Dice
Rolling two dice gives 36 equally likely outcomes. For "sum equals 7", there are 6 favorable outcomes: (1,6), (2,5), (3,4), (4,3), (5,2), (6,1).

P(sum = 7) = 6/36 = 1/6

Three steps to apply:

  1. Define the sample space and verify outcomes are equally likely
  2. Count total outcomes in S
  3. Count favorable outcomes in E
Key Insight
When all outcomes are equally likely, probability becomes counting. This is why we studied counting first!

Probability of OR

Mutually Exclusive Events

Two events E and F are mutually exclusive if they cannot both happen: E ∩ F = ∅. When events are mutually exclusive:

Addition Rule (Mutually Exclusive)
P(E or F) = P(E) + P(F)

For n mutually exclusive events:

P(E1 or E2 or … or En) = Σ P(Ei)

Inclusion-Exclusion Principle

When events can overlap, simple addition double-counts shared outcomes:

Inclusion-Exclusion (Two Events)
P(E or F) = P(E) + P(F) − P(E and F)

For three events:

P(E1 or E2 or E3) = P(E1) + P(E2) + P(E3)
− P(E1 and E2) − P(E1 and E3) − P(E2 and E3)
+ P(E1 and E2 and E3)

The pattern: add singles, subtract pairs, add triples, subtract quadruples…

Common Mistake
Incorrectly assuming events are mutually exclusive. If E = "even die roll" and S = "full sample space", then P(E or S) ≠ P(E) + P(S) = 0.5 + 1.0 = 1.5. The events overlap!
02 Conditional Probability

Conditional Probability

Definition

A conditional probability states: "what is the chance of E happening given that I have already observed F?" When you condition on F, you enter a universe where F has occurred—F becomes your new sample space.

Conditional Probability
P(E|F) = P(E and F) / P(F)
Example: Movie Recommendations
Netflix data shows: knowing someone watched Amélie increases the probability they'll watch Life is Beautiful from 2% to 9%.

P(Life is Beautiful | Amélie) ≈ (# who watched both) / (# who watched Amélie)

Why does knowing about Amélie change the probability? Because the two movies share an audience. Some probabilities go up, some go down, and some stay the same after conditioning.

The Conditional Paradigm

When you condition on an event G, you enter the universe where G has taken place. In that new universe, all the laws of probability still hold:

Original RuleConditioned on G
0 ≤ P(E) ≤ 10 ≤ P(E|G) ≤ 1
P(S) = 1P(S|G) = 1
P(E or F) = P(E) + P(F)P(E or F|G) = P(E|G) + P(F|G)
P(EC) = 1 − P(E)P(EC|G) = 1 − P(E|G)

Probability of AND

AND with Independent Events

If events are independent, the probability of and is simple multiplication:

AND for Independent Events
P(E and F) = P(E) · P(F)

For n mutually independent events:

P(E1 and E2 and … and En) = Π P(Ei)

AND with Dependent Events: The Chain Rule

For events that are not independent, we rearrange the definition of conditional probability:

The Chain Rule
P(E and F) = P(E|F) · P(F)

Equivalently: P(E and F) = P(F|E) · P(E)

The chain rule generalizes to more than two events:

P(E1 and E2 and … and En) = P(E1) · P(E2|E1) · P(E3|E1 and E2) · … · P(En|E1 … En−1)
Example: Drawing Cards
What is the probability of drawing two aces in a row from a standard deck (without replacement)?

P(Ace1 and Ace2) = P(Ace1) · P(Ace2|Ace1) = (4/52) · (3/51) = 12/2652 ≈ 0.0045
Summary: OR vs AND
OperationSpecial CaseGeneral Case
OR Mutually exclusive: P(E) + P(F) Inclusion-exclusion: P(E) + P(F) − P(E and F)
AND Independent: P(E) · P(F) Chain rule: P(E|F) · P(F)
03 Bayes' Theorem

Law of Total Probability

Any event E can be split into two parts: the part in F, and the part not in F. Since F and FC are mutually exclusive and cover the sample space:

P(E) = P(E and F) + P(E and FC)

Applying the chain rule to each term:

Law of Total Probability (LOTP)
P(E) = P(E|F) · P(F) + P(E|FC) · P(FC)

Generalized: If you can divide your sample space into mutually exclusive events B1, B2, …, Bn that cover all outcomes:

P(E) = Σ P(E|Bi) · P(Bi)
Example: Medical Testing by Risk Group
What is the probability a random person tests positive for a disease?

Divide the population into: high-risk (B1), medium-risk (B2), low-risk (B3).

P(Positive) = P(Pos|High) · P(High) + P(Pos|Med) · P(Med) + P(Pos|Low) · P(Low)

It's easier to think about the probability of testing positive within each group, then combine.
When to Use LOTP
Use the Law of Total Probability when you want P(E) but it's easier to compute P(E|Bi) for each of several "background" scenarios. It's the key tool for computing the denominator P(E) in Bayes' theorem.

Bayes' Theorem

Derivation

Start with the definition of conditional probability and the chain rule:

P(F|E) = P(F and E) / P(E) = P(E|F) · P(F) / P(E)

This lets you "flip" a conditional—when you know P(E|F) but need P(F|E):

Bayes' Theorem
P(B|E) = P(E|B) · P(B) / P(E)

Using the Law of Total Probability for the denominator:

Bayes' Theorem with LOTP
P(B|E) = P(E|B) · P(B) / [P(E|B) · P(B) + P(E|BC) · P(BC)]

Key Terminology

Prior P(B)
Your initial belief before observing evidence
Likelihood P(E|B)
Probability of the evidence given your belief is true
Posterior P(B|E)
Your updated belief after accounting for evidence
Normalizer P(E)
Ensures the result is a valid probability

When to Use Bayes' Theorem

Bayes' theorem is essential when you can easily compute P(Evidence|State) but need P(State|Evidence):

  • Medical testing: Know test accuracy given disease status; find disease probability given positive test
  • Student assessment: Know answer patterns given knowledge; infer understanding from responses
  • Spam filtering: Know word frequency in spam vs ham; classify new emails
  • Cell phone location: Know signal strength given distance; find location given signal

The pattern: an unobservable belief (B) causes observable evidence (E). We observe E and want to infer B.

Example: Medical Test
Disease prevalence: 8%. Test sensitivity: 95% (true positive rate). False positive rate: 7%.

If you test positive, what's the probability you have the disease?

P(Disease|+) = (0.95 × 0.08) / [(0.95 × 0.08) + (0.07 × 0.92)] = 0.076 / 0.140 ≈ 54%

Even with a positive test, there's only a 54% chance of actually having the disease!
Natural Frequency Intuition

Imagine 1000 people. 80 have the disease (8%), 920 don't.

  • Of the 80 with disease: 95% test positive = 76 true positives
  • Of the 920 without disease: 7% test positive = ~65 false positives
  • Total positive tests: 76 + 65 = 141
  • Fraction with disease: 76/141 ≈ 54%

Thinking in natural frequencies often makes Bayes' theorem more intuitive than plugging into the formula.

Example: Bacteria Evolution

10% of bacteria in a population have a mutation that makes them resistant to antibiotics. The probability that a bacterium with the mutation survives a course of antibiotics is 20%. Without the mutation, the survival probability is 1%.

What is P(a random bacterium survives)?

Using LOTP:

P(Survive) = P(Survive|Mutation) · P(Mutation) + P(Survive|No Mutation) · P(No Mutation)
= 0.20 × 0.10 + 0.01 × 0.90 = 0.029

What is P(a surviving bacterium has the mutation)?

Using Bayes' theorem:

P(Mutation|Survive) = P(Survive|Mutation) · P(Mutation) / P(Survive)
= (0.20 × 0.10) / 0.029 ≈ 69%

After antibiotics, 69% of surviving bacteria have the mutation—up from 10% before. This is natural selection in action!

Log Probabilities

A log probability is simply log P(E). Since 0 ≤ P(E) ≤ 1, log probabilities are always ≤ 0:

Log Probability Range
0 ≤ P(E) ≤ 1  ⇒  −∞ ≤ log P(E) ≤ 0

Why Use Log Probabilities?

  1. Products become sums: log(P(E) · P(F)) = log P(E) + log P(F). Computers are faster at addition than multiplication.
  2. Numerical stability: Python cannot represent probabilities smaller than ~2.225 × 10−308. But log(2.225 × 10−308) ≈ −307.65, which is easy to store.
Example: Document Probability
The probability that a given author wrote a specific 1000-word document involves multiplying ~1000 small probabilities together. In regular probability space, the result underflows to 0. In log space, it's a manageable negative number—and we can still compare which author is more likely.
Key Identity
log Π P(Ei) = Σ log P(Ei)

Many Coin Flips

Flip a coin n times, where each flip lands heads with probability p. This thought experiment is the basis for much of probability theory—it goes far beyond coins.

Warmups

P(all n heads)? Each flip is independent, so:

P(all heads) = pn

P(first k heads, then n−k tails)?

P(first k heads then n−k tails) = pk · (1−p)n−k

Exactly k Heads

What if we don't care where the heads appear, just that there are exactly k of them?

Any specific ordering with k heads and n−k tails has probability pk · (1−p)n−k. The key question: how many such orderings are there?

This is equivalent to: "how many distinct orderings of k H's and (n−k) T's?" — a permutations with repetition problem from Session 01:

Number of orderings = n! / (k! · (n−k)!) = C(n, k)

Since the orderings are mutually exclusive:

Probability of Exactly k Heads in n Flips
P(exactly k heads) = C(n, k) · pk · (1−p)n−k
Example: 4 Heads in 10 Flips (p = 0.6)
P(exactly 4 heads) = C(10, 4) · 0.64 · 0.46
= 210 · 0.1296 · 0.004096
= 210 · 0.000531
≈ 0.111
Why This Matters
This result is the foundation of the Binomial distribution—one of the most important distributions in statistics. Care about the number of voters who choose a candidate? Number of patients who respond to a treatment? Number of users who click an ad? All binomial.

More Than k Heads

Since the events "exactly i heads" for different values of i are mutually exclusive:

More Than k Heads
P(more than k heads) = Σi=k+1n C(n, i) · pi · (1−p)n−i

Worked Examples from the Course Reader

Part 1 of the course reader includes several extended examples that combine counting and probability. These are excellent practice:

Enigma Machine (p. 62)

How many unique configurations does the WWII Enigma machine have? Combines the product rule, combinations, and overcounting correction. Answer: ≈ 159 × 1018 settings.

Random Shuffles (p. 66)

If you shuffle a deck of cards 7 times, what's the probability your ordering has never occurred in all of human history? Uses equally likely outcomes, independence, and log probabilities. Answer: essentially 1.

Set Diversity & Gini Impurity (p. 71)

What is the probability that two randomly chosen objects from a set are different? Connects counting to the Gini Impurity measure used in Decision Trees and Random Forests.

Bacteria Evolution (p. 74)

How does antibiotic resistance spread? Uses LOTP and Bayes' theorem to show how natural selection works at the probability level.

04 Exclusive & Independent Events

Independence

Definition

Two events are independent if knowing one occurred doesn't change your belief about the other:

Independence
P(E|F) = P(E)

Equivalently (via the chain rule): P(E and F) = P(E) · P(F)

Key Properties

  • Symmetry: If E is independent of F, then F is independent of E
  • Complements: If E and F are independent, so are E and FC
  • Generalized: Events E1, …, En are independent if for every subset, the joint probability equals the product
Example: Coin Flips
Probability of 5 heads in 5 fair coin flips:

P(H1 and H2 and H3 and H4 and H5) = (1/2)5 = 1/32 ≈ 3.1%
Example: Parallel Networks
A network has n independent routers, each with probability pi of functioning. Information can be sent as long as at least one path works. What is P(network functional)?

P(functional) = 1 − P(all routers fail) = 1 − Π(1 − pi)

How to Establish Independence

Independence is either:

  1. Proven mathematically by showing P(E|F) = P(E)
  2. Declared as a modeling assumption when one event shouldn't influence belief about another
Independence ≠ Mutual Exclusion
These are very different! Mutually exclusive events are maximally dependent: if one happens, the other definitely didn't. Independent events are unrelated: one happening tells you nothing about the other.

Conditional Independence

Events can be independent when conditioned on some event F, even if they are not unconditionally independent (and vice versa):

P(E1, E2, E3|F) = P(E1|F) · P(E2|F) · P(E3|F)
Warning
Conditional independence given F does not imply unconditional independence. The independence property between events can change when you condition on a new event.
05 Random Variables

Part 2: Random Variables

Part 1 gave us the rules for working with events (scenarios). Part 2 introduces random variables—a formal language for describing uncertain quantities. Random variables let us model data, describe how systems behave, and reason rigorously under uncertainty.

Random Variables

Random Variable (RV)

A Random Variable is a variable that probabilistically takes on a value. You can think of an RV as being like a variable in a programming language: it has a type, takes on values, and has a domain over which it is applicable.

Example: Coin Flips
Let Y be the number of heads on three fair coin flips:
EventProbabilityOutcomes
Y = 01/8(T, T, T)
Y = 13/8(H, T, T), (T, H, T), (T, T, H)
Y = 23/8(H, H, T), (H, T, H), (T, H, H)
Y = 31/8(H, H, H)
Y ≥ 40—

Properties of a Random Variable

PropertyNotationDescription
SymbolXA letter used to denote the random variable
Support / Range{0, 1, …, 3}The values the RV can take on
Distribution FunctionP(X = x)Maps values to their probabilities (PMF or PDF)
ExpectationE[X]A weighted average
VarianceVar(X)A measure of spread
Standard DeviationStd(X)The square root of variance

Random Variables vs Events

An event is a scenario (an outcome or set of outcomes). A random variable is more like an experiment—it will take on an outcome eventually. Probabilities are over events, so to talk about probability in the context of an RV, you construct an event using relational operators: <, ≤, >, ≥, =, ≠

EventMeaningProbability Statement
Y = 1Y takes the value 1P(Y = 1)
Y < 2Y takes on 0 or 1P(Y < 2)
X > YX takes a value greater than YP(X > Y)
Y = yY takes on a non-random value yP(Y = y)
Convention
Capital letters (X, Y, Z) denote random variables. Lowercase letters (x, y, z) denote specific, non-random values.

Two Types of Random Variables

  • Discrete — can only take on integer values (e.g., number of heads, number of errors, class label)
  • Continuous — can take on decimal values (e.g., height, weight, time, temperature)

We develop our intuitions using discrete random variables first, then extend to continuous.

Why Random Variables Matter for This Course

In empirical research and system evaluation, random variables let you talk precisely about two things:

MotivationWhat RVs DoExample
Model Data Describe the probability of what a sample looks like X = digit label in MNIST; X ∼ Categorical over {0, …, 9}
Model Systems Describe how a system behaves under experimentation X = 1 if classifier is correct on a random test instance; X ∼ Bernoulli(p)

Once you have this language, you can reason under uncertainty:

  • Forward reasoning: “If my classifier has accuracy p = 0.8 and I test on n = 100 samples, how many correct?”
  • Backward reasoning: “I observed 80/100 correct. What can I conclude about true accuracy?”

Probability Mass Functions

Probability Mass Function (PMF)

For a discrete random variable, the PMF provides the probability for each possible value the RV can take on. It maps values to likelihoods:

P(X = x)   for each value x in the support of X
Example: Sum of Two Dice

If Y = sum of two dice, the PMF tells us P(Y = 2) = 1/36, P(Y = 3) = 2/36, …, P(Y = 7) = 6/36, …, P(Y = 12) = 1/36.

In Python:

def pmf_sum_two_dice(y):
    # Returns the probability that two dice sum to y
    if y < 2 or y > 12:
        return 0
    if y <= 7:
        return (y - 1) / 36
    else:
        return (13 - y) / 36

Probabilities Must Sum to 1

For X to be a proper random variable:

Σk P(X = k) = 1

Why? Each value is a mutually exclusive event, and X must take on some value. These mutually exclusive cases define the entire sample space.

From Data to Histograms to PMFs

A dataset is itself an approximation of a PMF. If you simulate summing two dice 10,000 times, the normalized histogram (count of each value / n) approximates the true PMF. By the empirical definition of probability, as n grows, the approximation improves.

Key Connection
Datasets in the real world often represent samples from an underlying distribution. The histogram is your window into the PMF.

Expectation

Expectation

The expectation of a random variable X, written E[X], is the average of all values weighted by their probabilities:

E[X] = Σx x · P(X = x)

Other names: Mean, Weighted Average, Center of Mass, 1st Moment.

Example: Sum of Two Dice

E[X] = 2 · (1/36) + 3 · (2/36) + … + 12 · (1/36) = 7

def expectation_sum_two_dice():
    exp = 0
    for x in range(2, 12 + 1):
        pr_x = pmf_sum_two_dice(x)
        exp += x * pr_x
    return exp  # returns 7.0

Properties of Expectation

Linearity of Expectation
E[aX + b] = a · E[X] + b
Expectation of the Sum of Random Variables
E[X + Y] = E[X] + E[Y]

This is true regardless of the relationship between X and Y—they can be dependent, independent, have different distributions. Generalizes to n variables: E[Σ Xi] = Σ E[Xi]

Law of the Unconscious Statistician (LOTUS)
E[g(X)] = Σx g(x) · P(X = x)

You can compute the expected value of any function g applied to X without knowing the distribution of g(X)—just use the distribution of X. Particularly useful for computing E[X²], which you need for variance.

Variance and Standard Deviation

Variance

Variance measures the spread of a random variable around its mean. With μ = E[X]:

Var(X) = E[(X − μ)²]

Computationally easier form:

Var(X) = E[X²] − (E[X])²
Example: Three Graders

Three sets of graders each grade an assignment worth 70/100:

  • Grader A: High spread—reasonable chance of giving 100 or 40. E[G] = 70, but Var(G) is large.
  • Grader B: Low spread—most grades cluster near 70. E[G] = 70, Var(G) is small.
  • Grader C: Different expectation—E[G] = 55, clearly biased.

You want graders like B: correct in expectation and low spread. Grader A is “noisy”—equally problematic but harder to detect.

Why This Matters
Total error isn't just bias—it's bias and variance. This will be central to Session 04 (Measurement) and Session 07 (Experiment Analysis).

Standard Deviation

Std(X) = √Var(X)

Variance has squared units (points², dollars²). Standard deviation is in the same units as X, making it more interpretable. “The spread of this grader is 7.2 points” is easier to understand than “the variance is 52 points².”

Properties of Variance

Var(aX + b) = a² · Var(X)

Adding a constant b shifts the distribution but doesn't change the spread. Multiplying by a scales the spread by a².

Parametric Distributions: Discrete

There are classic, commonly-seen random variable types in probability. If you can recognize that a random variable fits one of these types, you can use its pre-derived PMF, expectation, variance, and other properties. Think of them like classes in programming—you provide parameters and get all the properties for free.

Bernoulli Distribution

The simplest parametric distribution: a single binary outcome.

Bernoulli Random Variable
NotationX ∼ Bern(p)
DescriptionA boolean variable: 1 with probability p, 0 otherwise
Support{0, 1}
PMFP(X = x) = px(1 − p)1−x
E[X]p
Var(X)p(1 − p)

Examples: coin flip, whether a disk drive crashed, whether a user clicks an ad, whether a classifier is correct on a given instance.

Proof: E[X] = p

E[X] = Σx x · P(X = x) = 1 · p + 0 · (1 − p) = p

Proof: Var(X) = p(1 − p)

First compute E[X²] = 0² · (1 − p) + 1² · p = p

Var(X) = E[X²] − (E[X])² = p − p² = p(1 − p)

Indicator Random Variable

An indicator variable I is a Bernoulli RV that is 1 when an event A occurs and 0 otherwise. Key property: E[I] = P(A). This converts events into numbers—very useful for decomposing complex problems.

Binomial Distribution

The number of successes in n independent trials, each with probability p.

Binomial Random Variable
NotationX ∼ Bin(n, p)
DescriptionNumber of “successes” in n independent experiments, each with success probability p
Support{0, 1, …, n}
PMFP(X = k) = C(n, k) · pk · (1 − p)n−k
E[X]n · p
Var(X)n · p · (1 − p)

A binomial is the sum of n independent Bernoulli indicators: X = Σ Yi where each Yi ∼ Bern(p).

Examples: # of heads in n coin flips, # of 1’s in a random bit string, # of disk drives crashed in a cluster, # of correct predictions out of n test instances.

Proof: E[X] = np (using indicator decomposition)

Since X = Σ Yi and each Yi ∼ Bern(p):

E[X] = E[Σ Yi] = Σ E[Yi] = Σ p = n · p

This uses linearity of expectation—no need to compute the full PMF!

Connection to Part 1
Recall from “Many Coin Flips”: P(exactly k heads) = C(n,k) · pk(1−p)n−k. That is the Binomial PMF. We already derived it!

Binomial in Python

from scipy import stats

# P(X = 2) for X ~ Bin(n=5, p=0.6)
p_x = stats.binom.pmf(2, n=5, p=0.6)
print(f'P(X = 2) = {p_x:.4f}')  # 0.2304

# Generate 100 random samples from Bin(n=10, p=0.3)
samples = stats.binom.rvs(n=10, p=0.3, size=100)
print(samples)

Poisson Distribution

The probability of a given number of events in a fixed interval of time (or space), assuming events occur at a constant mean rate and independently of time since the last event.

Poisson Random Variable
NotationX ∼ Poi(λ)
DescriptionNumber of events in a fixed time frame at constant rate λ
Support{0, 1, 2, …}
PMFP(X = x) = λx · e−λ / x!
E[X]λ
Var(X)λ
Intuition: Poisson as a Binomial in the limit

Imagine counting ride-sharing requests per minute. Split the minute into n = 60 seconds; each second is a Bernoulli trial (request or not). With historical rate λ = 5, set p = λ/n = 5/60. Then X ∼ Bin(60, 5/60).

The approximation improves as we make intervals smaller (n → ∞, p = λ/n → 0). In the limit:

limn→∞ C(n,x) · (λ/n)x · (1 − λ/n)n−x = λx · e−λ / x!

The Poisson is a Binomial with infinitely many trials, each with infinitely small probability, but a finite expected count.

Other Discrete Distributions

DistributionNotationDescriptionE[X]Var(X)
Geometric X ∼ Geo(p) Number of experiments until first success 1/p (1 − p) / p²
Negative Binomial X ∼ NegBin(r, p) Number of experiments until r successes r/p r(1 − p) / p²
Categorical X ∼ Cat(p1, …, pk) One of k categories (non-numeric values) — —

The Geometric distribution answers: “How long until the first success?” (e.g., how many users until the first click). PMF: P(X = x) = (1 − p)x−1 · p.

The Categorical distribution handles non-numeric outcomes (e.g., weather: sunny, cloudy, rainy, snowy). Since values aren’t numbers, there is no expectation or variance—just a PMF as a table.

Continuous Random Variables

From Discrete to Continuous

So far, all our random variables have been discrete—they take on integer values. But many quantities (height, weight, time, temperature) can take on any real value. These are continuous random variables.

The key difference: for continuous RVs, the probability of any exact value is zero. (What is the probability a bus arrives at exactly 2:17pm and 12.1233391 seconds? Zero.) Instead, we talk about probabilities over ranges.

Probability Density Function (PDF)

X is a continuous random variable if there is a PDF f(x) such that:

P(a ≤ X ≤ b) = ∫ab f(x) dx

Properties: f(x) ≥ 0 everywhere, and ∫−∞∞ f(x) dx = 1.

Common Misconception
f(x) is not a probability—it is a probability density. It can be greater than 1! It only becomes a probability when integrated over a range.

Cumulative Distribution Function (CDF)

The CDF avoids solving integrals every time:

F(x) = P(X ≤ x) = ∫−∞x f(t) dt
Probability QuerySolution via CDF
P(X < a)F(a)
P(X > a)1 − F(a)
P(a < X < b)F(b) − F(a)
P(X = a)0  (for continuous RVs)

Expectation and Variance (Continuous)

For continuous RVs, sums become integrals:

E[X] = ∫−∞∞ x · f(x) dx

Var(X) = E[X²] − (E[X])²

Var(aX + b) = a² · Var(X)

All the properties of expectation (linearity, LOTUS, expectation of sums) hold for continuous RVs too.

Parametric Distributions: Continuous

Uniform Distribution

The simplest continuous distribution: equally likely to take on any value in a range.

Uniform Random Variable
NotationX ∼ Uni(α, β)
PDFf(x) = 1/(β − α) for α ≤ x ≤ β, else 0
E[X](α + β) / 2
Var(X)(β − α)² / 12
Example: Bus Stop

You arrive at 2:15pm. The bus arrives uniformly between 2:00pm and 2:30pm. T ∼ Uni(0, 30) in minutes after 2pm.

P(wait < 5 min) = P(15 < T < 20) = (20 − 15) / (30 − 0) = 5/30 ≈ 16.7%

Normal (Gaussian) Distribution

The most important continuous distribution. It arises naturally from the sum of many independent random variables (Central Limit Theorem, Session 04).

Normal Random Variable
NotationX ∼ N(μ, σ²)
PDFf(x) = (1 / σ√(2π)) · exp(−(x − μ)² / 2σ²)
CDFF(x) = Φ((x − μ) / σ)   where Φ is the standard normal CDF
E[X]μ
Var(X)σ²

Standard Normal: Z ∼ N(0, 1)

Any Normal X can be converted to the standard Normal: Z = (X − μ) / σ. Then FX(x) = Φ((x − μ) / σ).

Example: The 68-95-99.7 Rule

For any Normal distribution:

  • P(within 1σ of μ) ≈ 68.3%
  • P(within 2σ of μ) ≈ 95.4%
  • P(within 3σ of μ) ≈ 99.7%
from scipy import stats

# P(X > 0) for X ~ N(3, 16)  (mean=3, variance=16, so std=4)
p = 1 - stats.norm.cdf(0, loc=3, scale=4)
print(f'P(X > 0) = {p:.4f}')  # 0.7734

# Note: scipy uses standard deviation (scale), not variance!

Exponential Distribution

Measures the time until the next event in a Poisson process. (Poisson counts events in a fixed time; Exponential measures time between events.)

Exponential Random Variable
NotationX ∼ Exp(λ)
PDFf(x) = λ e−λx for x ≥ 0
CDFF(x) = 1 − e−λx
E[X]1/λ
Var(X)1/λ²
The Memoryless Property

The Exponential distribution is memoryless: P(X > s + t | X > s) = P(X > t).

Meaning: how long you’ve already waited tells you nothing about how much longer you’ll wait. Each moment is a fresh start.

Approximating the Binomial

Computing exact Binomial probabilities can be hard for large n. Two key approximations:

ApproximationWhen to UseFormula
Poisson n large (> 20), p small (< 0.05) Bin(n, p) ≈ Poi(λ = np)
Normal n large (> 20), p mid-ranged: np(1−p) > 10 Bin(n, p) ≈ N(np, np(1−p))

Normal Approximation of the Binomial

For large n with moderate p, the Binomial looks like a bell curve. Match the mean and variance:

X ∼ Bin(n, p)  ⇒  X ≈ Y ∼ N(np, np(1−p))
Example: A/B Test

100 visitors see a new design. Each converts independently with unknown probability p. Under the null hypothesis (p = 0.5, no effect), X ∼ Bin(100, 0.5).

E[X] = 50, Var(X) = 25, σ = 5. Using the Normal approximation:

P(X ≥ 65) ≈ P(Y > 64.5) = 1 − Φ((64.5 − 50)/5) = 1 − Φ(2.9) ≈ 0.0019

Only 0.2% chance under the null—strong evidence of a real effect.

Why This Matters
This Normal approximation of the Binomial is the foundation for confidence intervals and significance testing in Session 04. When you hear “plus or minus 1.96 standard errors,” this approximation is doing the work.

Distribution Summary

Discrete Distributions

DistributionPMFE[X]Var(X)Use Case
Bern(p) px(1−p)1−x p p(1−p) Single binary outcome
Bin(n, p) C(n,k)pk(1−p)n−k np np(1−p) Count of successes in n trials
Poi(λ) λxe−λ/x! λ λ Events in fixed time at rate λ
Geo(p) (1−p)x−1p 1/p (1−p)/p² Trials until first success

Continuous Distributions

DistributionPDFE[X]Var(X)Use Case
Uni(α, β) 1/(β−α) (α+β)/2 (β−α)²/12 Equally likely in a range
N(μ, σ²) (1/σ√2π)e−(x−μ)²/2σ² μ σ² Sum of many independent RVs
Exp(λ) λe−λx 1/λ 1/λ² Time until next event

Readings

Practice Problems

Problem Set 1
Counting & Probability

13 problems covering Sessions 01–02: seating, combinations, inclusion-exclusion, poker hands, grid paths, and more. Adapted from Stanford CS109.

Part 1: Core Probability

  1. A bag contains 5 red and 3 blue balls. You draw two balls without replacement. What is P(both red)? Use the chain rule.
  2. A rare disease affects 1 in 10,000 people. A test has 99% sensitivity and 99% specificity. If you test positive, what's the probability you have the disease?
  3. You flip a fair coin until you get heads. What is the probability it takes exactly 3 flips?
  4. Events A and B have P(A) = 0.4, P(B) = 0.3, P(A or B) = 0.6. Are A and B independent?
  5. In 10 fair coin flips, what is P(exactly 5 heads)? What is P(at least 8 heads)?
  6. A system has 3 independent components, each working with probability 0.9. What is P(at least one works)?
  7. If P(E) = 10−200 and P(F) = 10−150, and E and F are independent, compute log P(E and F).

Part 2: Random Variables

  1. A server cluster has 50 computers. Each crashes independently with probability 0.5. What is the standard deviation of the number of crashes? (Hint: identify the distribution.)
  2. A machine learning classifier makes 50 binary predictions, each independently correct with probability 6/25. What is P(at least 1 correct)?
  3. You are showing an ad to 30 people. Each person ignores it independently with probability 2/3. What is the expected number of ad clicks?
  4. Let X ∼ N(3, 16). What is P(X > 0)? What is P(2 < X < 5)?
  5. Earthquakes of magnitude 8.0+ occur at a rate of 0.002 per year. What is the probability of at least one in the next 4 years? (Hint: model the time until next event.)
  6. 100 visitors see a new website design. Under the null hypothesis that each converts with probability 0.5, what is P(65 or more conversions)? Use the Normal approximation.
  7. A random variable X has PMF: P(X = 1) = 0.3, P(X = 2) = 0.5, P(X = 3) = 0.2. Compute E[X], E[X²], and Var(X).

← Previous: Counting  ·  Next: The Science of Experimentation / I →