Skip to content
The Lumenary
Grades 9–12Ages 14–18 70 min

Conditional probability and independence

How new information changes a probability — tree diagrams, independence, the law of total probability, and Bayes' theorem, which explains why a positive test is not a diagnosis.

Formally verified · 22 LeanComputationally tested · 2 PythonAI-drafted · awaiting human reviewMathematically reviewed: Awaiting human review

Your guides: Chloe, Margaret, Gideon

MotivationH

You tested positive. Now what?

A screening test for a condition is described as "95% accurate": it detects 95%95\% of people who have the condition, and it gives a correct negative result for 95%95\% of people who do not. About 11 person in 100100 who take the test has the condition. You take the test, and the result is positive. How likely is it that you have the condition?

Most people answer "about 95%95\%". The true answer is about 16%16\%.

That is not a trick, and it is not a flaw in the test. It is what happens when we confuse two different questions — "how likely is a positive result, if you have the condition?" and "how likely is the condition, if your result is positive?" — and forget how rare the condition was to begin with. Doctors, juries, journalists and scientists have all made this mistake, sometimes with serious consequences. This lesson gives you the tools to get it right: conditional probability, independence and Bayes' theorem.

IntuitionH

New information shrinks the sample space

Roll two fair dice. The probability that the first die shows a 66 is 16\tfrac16. Now suppose a friend peeks and tells you: "the total is 1010". Only three of the 3636 equally likely outcomes are left:

(4,6),(5,5),(6,4).(4, 6), \quad (5, 5), \quad (6, 4).

In one of these three the first die shows a 66. So, given that the total is 1010, the probability that the first die is a 66 has risen from 16\tfrac16 to 13\tfrac13.

Conditioning on an event BB means throwing away every outcome outside BB and rescaling, so that the outcomes left over carry all the probability. Here is a second example, from a survey of 400400 secondary-school students in Hanoi about how they travel to school and whether they arrived late at least once last month:

latenot latetotal
cycle30170200
bus50150200
total80320400

Pick a student at random. P(late)=80400=0.2P(\text{late}) = \tfrac{80}{400} = 0.2. Among the cyclists only, P(late∣cycle)=30200=0.15P(\text{late} \mid \text{cycle}) = \tfrac{30}{200} = 0.15; among the bus riders, P(late∣bus)=50200=0.25P(\text{late} \mid \text{bus}) = \tfrac{50}{200} = 0.25. And among the late students, P(cycle∣late)=3080=0.375P(\text{cycle} \mid \text{late}) = \tfrac{30}{80} = 0.375 — a quite different number from 0.150.15, because it divides by a different total.

DefinitionsH

Definitions

We work, as in the lesson on probability, with a finite sample space Ω\Omega of outcomes. Each outcome ω\omega has a probability p(ω)≥0p(\omega) \ge 0, these add up to 11, and the probability of an event A⊆ΩA \subseteq \Omega is P(A)=∑ω∈Ap(ω)P(A) = \sum_{\omega \in A} p(\omega). Equally likely outcomes are the special case p(ω)=1/∣Ω∣p(\omega) = 1/|\Omega|, where P(A)=∣A∣/∣Ω∣P(A) = |A|/|\Omega|.

Definition— conditional probability

For events AA and BB with P(B)>0P(B) > 0, the conditional probability of AA given BB is

P(A∣B)=P(A∩B)P(B).P(A \mid B) = \frac{P(A \cap B)}{P(B)}.

It is not defined when P(B)=0P(B) = 0.

Definition— independent events

Events AA and BB are independent if P(A∩B)=P(A) P(B)P(A \cap B) = P(A)\,P(B).

Definition— mutually exclusive events

Events AA and BB are mutually exclusive if they cannot both happen: A∩B=∅A \cap B = \varnothing.

Definition— partition

Events B1,…,BnB_1, \dots, B_n partition the sample space if they are pairwise mutually exclusive and together cover it: every outcome lies in exactly one BiB_i. For example, BB and its complement BcB^c form a partition.

The definition of independence is symmetric in AA and BB and makes sense even when a probability is 00; Theorem 5 below explains why it captures the idea "knowing BB tells us nothing about AA".

Worked examplesH

Worked examples

Example— Two cards without replacement

Draw two cards from a shuffled pack of 5252, without putting the first back. What is the probability that both are aces? The first is an ace with probability 452\tfrac{4}{52}. Given that it was, 5151 cards remain, of which 33 are aces, so the second is an ace with conditional probability 351\tfrac{3}{51}. Multiplying along the branches of the tree,

P(both aces)=452×351=122652=1221.P(\text{both aces}) = \frac{4}{52} \times \frac{3}{51} = \frac{12}{2652} = \frac{1}{221}.

The draws are not independent: P(2nd ace∣1st ace)=351≠452=P(2nd ace)P(\text{2nd ace} \mid \text{1st ace}) = \tfrac{3}{51} \ne \tfrac{4}{52} = P(\text{2nd ace}).

Example— Independent events from dice

Roll two dice. Let AA = "the first die is even" and BB = "the total is 77". Then P(A)=1836=12P(A) = \tfrac{18}{36} = \tfrac12, P(B)=636=16P(B) = \tfrac{6}{36} = \tfrac16, and A∩B={(2,5),(4,3),(6,1)}A \cap B = \{(2, 5), (4, 3), (6, 1)\}, so P(A∩B)=336=112=P(A) P(B)P(A \cap B) = \tfrac{3}{36} = \tfrac1{12} = P(A)\,P(B). They are independent: whatever the first die shows, exactly one face of the second die makes the total 77.

By contrast, CC = "the first die is 66" and DD = "the total is at least 1010" are not independent: P(C∩D)=336P(C \cap D) = \tfrac{3}{36}, but P(C) P(D)=16⋅16=136P(C)\,P(D) = \tfrac16 \cdot \tfrac16 = \tfrac{1}{36}.

Example— Mutually exclusive is not independent

With one die, "roll a 11" and "roll a 66" are mutually exclusive. Are they independent? P(both)=0P(\text{both}) = 0, but P(1) P(6)=136≠0P(1)\,P(6) = \tfrac{1}{36} \ne 0. No — learning that you rolled a 66 tells you for certain that you did not roll a 11. Mutually exclusive events with positive probabilities are as far from independent as can be.

Example— Pairwise is not enough

Toss two fair coins. Let AA = "the first is heads", BB = "the second is heads", CC = "the two coins show the same face". Each has probability 12\tfrac12, and each pair is independent: for instance A∩CA \cap C = "both heads" has probability 14=12⋅12\tfrac14 = \tfrac12 \cdot \tfrac12. But AA and BB together force CC: P(A∩B∩C)=14≠18=P(A)P(B)P(C)P(A \cap B \cap C) = \tfrac14 \ne \tfrac18 = P(A)P(B)P(C). For three events to be (mutually) independent we require the product rule for every pair and for all three together.

ProofH

The rules, with proofs

Throughout, Ω\Omega is a finite sample space with probabilities p(ω)p(\omega) as above.

Theorem— Theorem 1 (basic rules)

For all events AA and BB: if A∩B=∅A \cap B = \varnothing then P(A∪B)=P(A)+P(B)P(A \cup B) = P(A) + P(B); in general

P(A∪B)=P(A)+P(B)−P(A∩B),P(Ac)=1−P(A).P(A \cup B) = P(A) + P(B) - P(A \cap B), \qquad P(A^c) = 1 - P(A).

Proof

If AA and BB are disjoint, the sum of p(ω)p(\omega) over A∪BA \cup B splits into the sum over AA plus the sum over BB. In general, P(A)+P(B)P(A) + P(B) adds p(ω)p(\omega) twice for each ω∈A∩B\omega \in A \cap B and once for every other outcome of A∪BA \cup B; subtract P(A∩B)P(A \cap B). Finally AA and AcA^c are disjoint with union Ω\Omega, so P(A)+P(Ac)=P(Ω)=1P(A) + P(A^c) = P(\Omega) = 1.

∎

Theorem— Theorem 2 (conditioning gives a new probability)

Fix an event BB with P(B)>0P(B) > 0. Then A↦P(A∣B)A \mapsto P(A \mid B) is again a probability: 0≤P(A∣B)≤10 \le P(A \mid B) \le 1, P(Ω∣B)=P(B∣B)=1P(\Omega \mid B) = P(B \mid B) = 1, and P(A1∪A2∣B)=P(A1∣B)+P(A2∣B)P(A_1 \cup A_2 \mid B) = P(A_1 \mid B) + P(A_2 \mid B) when A1∩A2=∅A_1 \cap A_2 = \varnothing.

Proof

Since A∩B⊆BA \cap B \subseteq B, we have 0≤P(A∩B)≤P(B)0 \le P(A \cap B) \le P(B); divide by P(B)P(B). Next, P(Ω∩B)=P(B)P(\Omega \cap B) = P(B). If A1A_1 and A2A_2 are disjoint, so are A1∩BA_1 \cap B and A2∩BA_2 \cap B, and their union is (A1∪A2)∩B(A_1 \cup A_2) \cap B; apply Theorem 1 and divide by P(B)P(B).

∎

In fact P( ⋅∣B)P(\,\cdot \mid B) gives each outcome ω∈B\omega \in B the new probability p(ω)/P(B)p(\omega)/P(B) and each outcome outside BB probability 00: the "throw away and rescale" of the intuition section. So every rule of probability holds for conditional probabilities too — for instance P(Ac∣B)=1−P(A∣B)P(A^c \mid B) = 1 - P(A \mid B).

Theorem— Theorem 3 (multiplication rule)

If P(B)>0P(B) > 0 then P(A∩B)=P(A∣B) P(B)P(A \cap B) = P(A \mid B)\,P(B). More generally, if P(A1∩A2)>0P(A_1 \cap A_2) > 0,

P(A1∩A2∩A3)=P(A1) P(A2∣A1) P(A3∣A1∩A2).P(A_1 \cap A_2 \cap A_3) = P(A_1)\,P(A_2 \mid A_1)\,P(A_3 \mid A_1 \cap A_2).

Proof

The first statement is the definition of P(A∣B)P(A \mid B) multiplied by P(B)P(B). For the second, write out the right-hand side: P(A1)⋅P(A1∩A2)P(A1)⋅P(A1∩A2∩A3)P(A1∩A2)P(A_1) \cdot \dfrac{P(A_1 \cap A_2)}{P(A_1)} \cdot \dfrac{P(A_1 \cap A_2 \cap A_3)}{P(A_1 \cap A_2)}; everything cancels except P(A1∩A2∩A3)P(A_1 \cap A_2 \cap A_3). (Both denominators are positive, since P(A1)≥P(A1∩A2)>0P(A_1) \ge P(A_1 \cap A_2) > 0.)

∎

This is why we multiply along the branches of a tree diagram: each branch carries a conditional probability, given everything on the path before it.

Theorem— Theorem 4 (law of total probability)

If B1,…,BnB_1, \dots, B_n partition Ω\Omega and each P(Bi)>0P(B_i) > 0, then for every event AA,

P(A)=∑i=1nP(A∣Bi) P(Bi).P(A) = \sum_{i=1}^{n} P(A \mid B_i)\,P(B_i).

In particular, if 0<P(B)<10 < P(B) < 1:   P(A)=P(A∣B) P(B)+P(A∣Bc) P(Bc)\;P(A) = P(A \mid B)\,P(B) + P(A \mid B^c)\,P(B^c).

Proof

Every outcome of AA lies in exactly one BiB_i, so AA is the union of the pairwise disjoint pieces A∩B1,…,A∩BnA \cap B_1, \dots, A \cap B_n, and P(A)=∑iP(A∩Bi)P(A) = \sum_i P(A \cap B_i) by Theorem 1 (applied repeatedly). By the multiplication rule, P(A∩Bi)=P(A∣Bi) P(Bi)P(A \cap B_i) = P(A \mid B_i)\,P(B_i).

∎

On a tree diagram: to find P(A)P(A), add up the probabilities of all the paths that end in AA.

Theorem— Theorem 5 (Bayes' theorem)

If P(A)>0P(A) > 0 and P(B)>0P(B) > 0, then

P(A∣B)=P(B∣A) P(A)P(B).P(A \mid B) = \frac{P(B \mid A)\,P(A)}{P(B)}.

Combined with Theorem 4, when 0<P(A)<10 < P(A) < 1:

P(A∣B)=P(B∣A) P(A)P(B∣A) P(A)+P(B∣Ac) P(Ac).P(A \mid B) = \frac{P(B \mid A)\,P(A)}{P(B \mid A)\,P(A) + P(B \mid A^c)\,P(A^c)}.

Proof

By the multiplication rule, used twice, P(A∣B) P(B)=P(A∩B)=P(B∩A)=P(B∣A) P(A)P(A \mid B)\,P(B) = P(A \cap B) = P(B \cap A) = P(B \mid A)\,P(A). Divide by P(B)P(B). For the second form, expand the denominator P(B)P(B) by the law of total probability with the partition A,AcA, A^c.

∎

Bayes' theorem reverses a conditional probability. It needs one extra ingredient: the base rate (or prior probability) P(A)P(A).

Example— The screening test, solved

Let DD = "has the condition" and TT = "tests positive". We know P(D)=0.01P(D) = 0.01, P(T∣D)=0.95P(T \mid D) = 0.95 and P(T∣Dc)=0.05P(T \mid D^c) = 0.05. By Bayes' theorem,

P(D∣T)=0.95×0.010.95×0.01+0.05×0.99=0.00950.059=19118≈0.161.P(D \mid T) = \frac{0.95 \times 0.01}{0.95 \times 0.01 + 0.05 \times 0.99} = \frac{0.0095}{0.059} = \frac{19}{118} \approx 0.161.

Natural frequencies make this transparent. Imagine 10 00010\,000 people. About 100100 have the condition, and 9595 of them test positive. Of the 9 9009\,900 who do not, 5%5\% — that is 495495 — also test positive. So of the 95+495=59095 + 495 = 590 positive results, only 9595 come from people with the condition: 95590≈16%\tfrac{95}{590} \approx 16\%. The false positives outnumber the true ones because healthy people are so much more numerous.

0.010.990.950.050.050.95Dnot DT: 0.0095not T: 0.0005T: 0.0495not T: 0.9405
The screening test as a tree. Multiply along each path; the two paths ending in a positive result have probabilities $0.0095$ and $0.0495$, so $P(T) = 0.059$ and $P(D \mid T) = 0.0095 / 0.059 \approx 0.16$.

Independence

Theorem— Theorem 6 (independence as irrelevance)

If P(B)>0P(B) > 0, then AA and BB are independent if and only if P(A∣B)=P(A)P(A \mid B) = P(A).

Proof

P(A∣B)=P(A)P(A \mid B) = P(A) means P(A∩B)P(B)=P(A)\dfrac{P(A \cap B)}{P(B)} = P(A), which (multiplying by P(B)>0P(B) > 0) is the same as P(A∩B)=P(A) P(B)P(A \cap B) = P(A)\,P(B).

∎

Theorem— Theorem 7 (complements)

If AA and BB are independent, so are AA and BcB^c (and hence also AcA^c and BB, and AcA^c and BcB^c).

Proof

AA is the disjoint union of A∩BA \cap B and A∩BcA \cap B^c, so

P(A∩Bc)=P(A)−P(A∩B)=P(A)−P(A)P(B)=P(A)(1−P(B))=P(A) P(Bc),P(A \cap B^c) = P(A) - P(A \cap B) = P(A) - P(A)P(B) = P(A)\big(1 - P(B)\big) = P(A)\,P(B^c),

using independence in the second step and the complement rule in the last. Applying this again with the roles of the events exchanged gives the other two statements.

∎

Theorem— Theorem 8 (exclusive events are dependent)

If AA and BB are mutually exclusive and P(A)>0P(A) > 0, P(B)>0P(B) > 0, then AA and BB are not independent.

Proof

P(A∩B)=P(∅)=0P(A \cap B) = P(\varnothing) = 0, while P(A) P(B)>0P(A)\,P(B) > 0.

∎

Formal mathematicsF

The rules, checked by Lean

We formalise a finite probability space exactly as in the definitions: a finite type of outcomes and a rational probability for each, adding up to 11. Using rational numbers keeps every calculation exact.

FinProbLean 4Formally verified
/-- A **finite probability space** on a finite type of outcomes `Ω`: a probability `p ω ≥ 0`
for each outcome, adding up to `1`. -/
structure FinProb (Ω : Type*) [Fintype Ω] where
  /-- the probability of each single outcome -/
  p : Ω → ℚ
  nonneg : ∀ ω, 0 ≤ p ω
  sum_eq_one : ∑ ω, p ω = 1
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor
PLean 4Formally verified
/-- The **probability of an event** `A` (a set of outcomes): the sum of the probabilities of
its outcomes. -/
def FinProb.P {Ω : Type*} [Fintype Ω] (μ : FinProb Ω) (A : Finset Ω) : ℚ :=
  ∑ ω ∈ A, μ.p ω
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor
condLean 4Formally verified
/-- **Conditional probability:** `P(A | B) = P(A ∩ B) / P(B)`, the probability of `A` when we
know that `B` happened. It is meant to be used only when `P(B) > 0`; Lean's convention `x / 0 = 0`
gives it the meaningless value `0` otherwise, and every theorem below that needs `P(B) ≠ 0`
assumes it. -/
def FinProb.cond {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω) (A B : Finset Ω) : ℚ :=
  μ.P (A ∩ B) / μ.P B
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor
IndepLean 4Formally verified
/-- Events `A` and `B` are **independent** when `P(A ∩ B) = P(A) P(B)`. -/
def FinProb.Indep {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω) (A B : Finset Ω) :
    Prop :=
  μ.P (A ∩ B) = μ.P A * μ.P B
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor

The basic rules (Theorem 1) and the multiplication rule:

prob_complLean 4Proved here from basic factsFormally verified
/-- **Complement rule:** `P(Aᶜ) = 1 − P(A)`. The outcomes of `A` and of `Aᶜ` together are all
the outcomes, whose probabilities add up to `1`. -/
theorem prob_compl {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω) (A : Finset Ω) :
    μ.P Aᶜ = 1 - μ.P A := by
  have h := sum_add_sum_compl A μ.p
  rw [μ.sum_eq_one] at h
  unfold P
  linarith
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor
prob_unionLean 4Proved here from basic factsFormally verified
/-- **Addition rule:** `P(A ∪ B) = P(A) + P(B) − P(A ∩ B)`: adding `P(A)` and `P(B)` counts the
outcomes of `A ∩ B` twice. -/
theorem prob_union {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω) (A B : Finset Ω) :
    μ.P (A ∪ B) = μ.P A + μ.P B - μ.P (A ∩ B) := by
  have h := sum_union_inter (s₁ := A) (s₂ := B) (f := μ.p)
  unfold P
  linarith
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor
mul_ruleLean 4Proved here from basic factsFormally verified
/-- **Multiplication rule:** `P(A ∩ B) = P(A | B) · P(B)` whenever `P(B) ≠ 0` — "multiply along
the branches of the tree". It is the definition of `P(A | B)`, rearranged. -/
theorem mul_rule {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω) (A B : Finset Ω)
    (hB : μ.P B ≠ 0) : μ.P (A ∩ B) = μ.cond A B * μ.P B := by
  rw [cond, div_mul_cancel₀ _ hB]
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor

Bayes' theorem and the law of total probability (Theorems 4 and 5), and the screening test as a theorem about every probability space with those three numbers:

bayesLean 4Proved here from basic factsFormally verified
/-- **Bayes' theorem:** `P(A | B) = P(B | A) P(A) / P(B)` when `P(A) ≠ 0`. Both `P(A | B) P(B)`
and `P(B | A) P(A)` equal `P(A ∩ B)`: the same probability, computed along two different
trees. -/
theorem bayes {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω) (A B : Finset Ω)
    (hA : μ.P A ≠ 0) : μ.cond A B = μ.cond B A * μ.P A / μ.P B := by
  rw [← mul_rule μ B A hA, inter_comm, cond]
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor
total_probabilityLean 4Proved here from basic factsFormally verified
/-- **Law of total probability.** If the events `B i` (for `i ∈ s`) are pairwise disjoint,
cover every outcome, and each has positive probability, then `P(A) = Σᵢ P(A | Bᵢ) P(Bᵢ)`.
Proof: `A` is the disjoint union of the pieces `A ∩ Bᵢ`, so `P(A) = Σᵢ P(A ∩ Bᵢ)`, and each
piece is `P(A | Bᵢ) P(Bᵢ)` by the multiplication rule. -/
theorem total_probability {Ω ι : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω)
    (A : Finset Ω) (s : Finset ι) (B : ι → Finset Ω) (hdisj : (s : Set ι).PairwiseDisjoint B)
    (hcover : ∀ ω, ∃ i ∈ s, ω ∈ B i) (hpos : ∀ i ∈ s, μ.P (B i) ≠ 0) :
    μ.P A = ∑ i ∈ s, μ.cond A (B i) * μ.P (B i) := by
  -- `A` is the disjoint union of the pieces `A ∩ B i`
  have hA : A = s.biUnion fun i => A ∩ B i := by
    ext ω
    simp only [mem_biUnion, mem_inter]
    constructor
    · intro hω
      obtain ⟨i, hi, hωi⟩ := hcover ω
      exact ⟨i, hi, hω, hωi⟩
    · rintro ⟨i, -, hω, -⟩
      exact hω
  have hdisj' : (s : Set ι).PairwiseDisjoint fun i => A ∩ B i := by
    intro i hi j hj hij
    exact Disjoint.mono inter_subset_right inter_subset_right (hdisj hi hj hij)
  calc μ.P A = ∑ ω ∈ s.biUnion (fun i => A ∩ B i), μ.p ω := by rw [← hA]; rfl
    _ = ∑ i ∈ s, μ.P (A ∩ B i) := sum_biUnion hdisj'
    _ = ∑ i ∈ s, μ.cond A (B i) * μ.P (B i) :=
      sum_congr rfl fun i hi => mul_rule μ A (B i) (hpos i hi)
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor
total_probability_twoLean 4Proved here from basic factsFormally verified
/-- **Total probability with two cases:** `P(A) = P(A | B) P(B) + P(A | Bᶜ) P(Bᶜ)` when
`0 < P(B) < 1`. Either `B` happens or it does not. -/
theorem total_probability_two {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω)
    (A B : Finset Ω) (hB : μ.P B ≠ 0) (hBc : μ.P Bᶜ ≠ 0) :
    μ.P A = μ.cond A B * μ.P B + μ.cond A Bᶜ * μ.P Bᶜ := by
  rw [← mul_rule μ A B hB, ← mul_rule μ A Bᶜ hBc]
  have h := sum_filter_add_sum_filter_not A (· ∈ B) μ.p
  have e1 : A.filter (· ∈ B) = A ∩ B := by ext; simp [mem_inter]
  have e2 : A.filter (· ∉ B) = A ∩ Bᶜ := by ext; simp [mem_inter]
  rw [e1, e2] at h
  unfold P
  linarith
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor
bayes_totalLean 4Proved here from basic factsFormally verified
/-- **Bayes' theorem for a test result.** With `D` = "has the condition" and `T` = "tests
positive",
`P(D | T) = P(T | D) P(D) / (P(T | D) P(D) + P(T | Dᶜ) P(Dᶜ))`:
Bayes' theorem with the denominator `P(T)` expanded by total probability. -/
theorem bayes_total {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω) (D T : Finset Ω)
    (hD : μ.P D ≠ 0) (hDc : μ.P Dᶜ ≠ 0) :
    μ.cond D T = μ.cond T D * μ.P D / (μ.cond T D * μ.P D + μ.cond T Dᶜ * μ.P Dᶜ) := by
  rw [bayes μ D T hD, ← total_probability_two μ T D hD hDc]
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor
base_rate_exampleLean 4Proved here from basic factsFormally verified
/-- **A positive test is not a diagnosis.** Suppose `1%` of people have a condition, the test
detects it `95%` of the time (`P(T | D) = 0.95`), and it wrongly flags `5%` of healthy people
(`P(T | Dᶜ) = 0.05`). Then a positive result means only `P(D | T) = 19/118 ≈ 16%`. The base rate
`P(D) = 0.01` matters as much as the accuracy of the test. -/
theorem base_rate_example {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω)
    (D T : Finset Ω) (hD : μ.P D = 1 / 100) (hTD : μ.cond T D = 95 / 100)
    (hTDc : μ.cond T Dᶜ = 5 / 100) : μ.cond D T = 19 / 118 := by
  have hDc : μ.P Dᶜ = 99 / 100 := by rw [prob_compl, hD]; norm_num
  rw [bayes_total μ D T (by rw [hD]; norm_num) (by rw [hDc]; norm_num), hD, hDc, hTD, hTDc]
  norm_num
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor

Independence (Theorems 6, 7 and 8):

indep_iff_condLean 4Proved here from basic factsFormally verified
/-- **Independence means "knowing `B` tells us nothing about `A`":** when `P(B) ≠ 0`, `A` and
`B` are independent exactly when `P(A | B) = P(A)`. -/
theorem indep_iff_cond {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω)
    (A B : Finset Ω) (hB : μ.P B ≠ 0) : μ.Indep A B ↔ μ.cond A B = μ.P A := by
  rw [Indep, cond, div_eq_iff hB]
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor
exclusive_not_indepLean 4Proved here from basic factsFormally verified
/-- **Mutually exclusive is the opposite of independent.** If `A` and `B` cannot both happen
and each has positive probability, they are *not* independent: `P(A ∩ B) = 0`, but
`P(A) P(B) > 0`. Learning that `B` happened tells us for certain that `A` did not. -/
theorem exclusive_not_indep {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω)
    (A B : Finset Ω) (hdisj : A ∩ B = ∅) (hA : μ.P A ≠ 0) (hB : μ.P B ≠ 0) :
    ¬ μ.Indep A B := by
  intro h
  rw [Indep, hdisj] at h
  have h0 : μ.P ∅ = 0 := sum_empty
  rw [h0] at h
  exact mul_ne_zero hA hB h.symm
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor
indep_complLean 4Proved here from basic factsFormally verified
/-- **Independence survives complements:** if `A` and `B` are independent, so are `A` and
`Bᶜ`. Proof: `P(A ∩ Bᶜ) = P(A) − P(A ∩ B) = P(A) − P(A) P(B) = P(A)(1 − P(B)) = P(A) P(Bᶜ)`. -/
theorem indep_compl {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω) (A B : Finset Ω)
    (h : μ.Indep A B) : μ.Indep A Bᶜ := by
  have hsplit := sum_filter_add_sum_filter_not A (· ∈ B) μ.p
  have e1 : A.filter (· ∈ B) = A ∩ B := by ext; simp [mem_inter]
  have e2 : A.filter (· ∉ B) = A ∩ Bᶜ := by ext; simp [mem_inter]
  rw [e1, e2] at hsplit
  have hc := prob_compl μ B
  unfold Indep at h ⊢
  rw [hc]
  unfold P at *
  rw [mul_sub, mul_one]
  linarith
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor

For equally likely outcomes, probability is counting, and independence becomes a statement about counts that Lean can check by listing all 3636 outcomes of two dice:

uniformLean 4Formally verified
/-- **Equally likely outcomes:** each of the `|Ω|` outcomes has probability `1/|Ω|`. -/
def uniform (Ω : Type*) [Fintype Ω] [Nonempty Ω] : FinProb Ω where
  p _ := 1 / Fintype.card Ω
  nonneg _ := by positivity
  sum_eq_one := by
    rw [sum_const, card_univ, nsmul_eq_mul]
    have : (Fintype.card Ω : ℚ) ≠ 0 := by exact_mod_cast Fintype.card_ne_zero
    field_simp
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor
uniform_PLean 4Proved here from basic factsFormally verified
/-- With equally likely outcomes, `P(A) = |A| / |Ω|`: probability is counting, divided. -/
theorem uniform_P {Ω : Type*} [Fintype Ω] [Nonempty Ω] (A : Finset Ω) :
    (uniform Ω).P A = #A / Fintype.card Ω := by
  simp only [P, uniform, sum_const, nsmul_eq_mul]
  ring
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor
uniform_indep_iffLean 4Proved here from basic factsFormally verified
/-- With equally likely outcomes, independence is a statement about counting:
`A` and `B` are independent exactly when `|A ∩ B| · |Ω| = |A| · |B|`. -/
theorem uniform_indep_iff {Ω : Type*} [Fintype Ω] [DecidableEq Ω] [Nonempty Ω]
    (A B : Finset Ω) : (uniform Ω).Indep A B ↔ #(A ∩ B) * Fintype.card Ω = #A * #B := by
  have hN : (Fintype.card Ω : ℚ) ≠ 0 := by exact_mod_cast Fintype.card_ne_zero
  rw [Indep, uniform_P, uniform_P, uniform_P, div_mul_div_comm,
    div_eq_div_iff hN (mul_ne_zero hN hN)]
  constructor
  · intro h
    have h' : ((#(A ∩ B) : ℚ) * Fintype.card Ω) * Fintype.card Ω =
        ((#A : ℚ) * #B) * Fintype.card Ω := by
      rw [mul_assoc]
      exact h
    exact_mod_cast mul_right_cancel₀ hN h'
  · intro h
    have h' : ((#(A ∩ B) : ℚ) * Fintype.card Ω) = (#A : ℚ) * #B := by exact_mod_cast h
    rw [← mul_assoc, h']
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor
dice_even_sevenLean 4Proved here from basic factsFormally verified
/-- **Two dice, independent events.** Roll two fair dice (outcome `(i, j)` means faces `i + 1`
and `j + 1`). "The first die is even" and "the total is 7" are independent:
`P(both) = 3/36 = 1/12 = (18/36)(6/36)`. Lean counts the outcomes: `3 · 36 = 18 · 6`. -/
theorem dice_even_seven :
    (uniform (Fin 6 × Fin 6)).Indep
      {ω | (ω.1.val + 1) % 2 = 0} {ω | ω.1.val + ω.2.val + 2 = 7} :=
  (uniform_indep_iff _ _).2 (by decide)
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor
dice_six_highLean 4Proved here from basic factsFormally verified
/-- **Two dice, dependent events.** "The first die shows 6" and "the total is at least 10" are
*not* independent: `P(both) = 3/36 = 1/12`, but `P(first is 6) P(total ≥ 10) = (1/6)(1/6) = 1/36`.
Knowing that the first die is a 6 makes a high total three times as likely. Lean counts:
`3 · 36 ≠ 6 · 6`. -/
theorem dice_six_high :
    ¬ (uniform (Fin 6 × Fin 6)).Indep
      {ω | ω.1.val + 1 = 6} {ω | 10 ≤ ω.1.val + ω.2.val + 2} := by
  rw [uniform_indep_iff]
  decide
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor

At university, probability is built on measure theory, which also handles infinitely many outcomes (a point chosen at random on a line, a random walk that goes on forever). Mathlib's probability library is written in that language; here are Bayes' theorem and total probability as it states them. The notation μ[t | s] is P(t∣s)P(t \mid s), and probabilities take values in [0,∞][0, \infty]:

bayes_libraryLean 4Applies a library theoremFormally verified
/-- **Bayes' theorem** for any finite measure (in particular any probability measure), with
`μ[t | s]` the conditional probability of `t` given `s`:
`P(t | s) = P(s)⁻¹ · P(s | t) · P(t)`. Probabilities here take values in `[0, ∞]`, so no
positivity hypothesis is needed: `0⁻¹ = ∞` and the conventions are arranged to make the identity
true. This applies Mathlib's `ProbabilityTheory.cond_eq_inv_mul_cond_mul`. -/
theorem bayes_library {Ω : Type*} [MeasurableSpace Ω] (μ : Measure Ω) [IsFiniteMeasure μ]
    {s t : Set Ω} (hs : MeasurableSet s) (ht : MeasurableSet t) :
    μ[t | s] = (μ s)⁻¹ * μ[s | t] * μ t :=
  cond_eq_inv_mul_cond_mul hs ht μ
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor
total_probability_libraryLean 4Applies a library theoremFormally verified
/-- **Total probability with two cases**, for any finite measure:
`P(t | s) P(s) + P(t | sᶜ) P(sᶜ) = P(t)`. This applies Mathlib's
`ProbabilityTheory.cond_add_cond_compl_eq`. -/
theorem total_probability_library {Ω : Type*} [MeasurableSpace Ω] (μ : Measure Ω)
    [IsFiniteMeasure μ] {s t : Set Ω} (hs : MeasurableSet s) :
    μ[t | s] * μ s + μ[t | sᶜ] * μ sᶜ = μ t :=
  cond_add_cond_compl_eq hs μ
Axioms used: propext, Classical.choice, Quot.soundformal/Lumenary/ProbabilityRules.leanTry it in the Lean web editor

Our finite spaces are a special case of Mathlib's measures; we have not formally proved that the two notions of conditional probability agree on them, though they do.

ComputationC

Tables and simulations

Bayes' theorem with natural frequencies and base ratesPythonExact computationComputationally tested
"""Bayes' theorem with natural frequencies: tests, base rates and courtrooms.

A diagnostic test is imagined on 100,000 people and every count is exact.
The two-way table shows why P(condition | positive) and P(positive |
condition) are different numbers, and the same test is re-run with base
rates from 0.1% to 50% to show how strongly the answer depends on them. A
second independent positive test is handled by using the first posterior as
the new prior. Finally the prosecutor's fallacy: a DNA profile shared by one
person in a million, in a city of two million.
"""

from fractions import Fraction

def two_way_table(population, prevalence, sensitivity, specificity):
    """Counts (true pos, false neg, false pos, true neg) as exact Fractions."""
    sick = population * prevalence
    well = population - sick
    return (sick * sensitivity, sick * (1 - sensitivity),
            well * (1 - specificity), well * specificity)

def posterior(prior, p_pos_given_d, p_pos_given_not_d):
    """P(D | positive) by Bayes' theorem with total probability below."""
    top = p_pos_given_d * prior
    return top / (top + p_pos_given_not_d * (1 - prior))

def fmt(q):
    """An exact count as a whole number with thousands separators."""
    assert q.denominator == 1
    return f"{q.numerator:,}"

def main():
    sens, spec = Fraction(95, 100), Fraction(95, 100)
    tp, fn, fp, tn = two_way_table(Fraction(100000), Fraction(1, 100),
                                   sens, spec)
    print("Test: sensitivity 95%, specificity 95%; base rate 1%.")
    print("Imagine 100,000 people:")
    print("                  test +     test -      total")
    print(f"  condition    {fmt(tp):>9}  {fmt(fn):>9}  {fmt(tp + fn):>9}")
    print(f"  no condition {fmt(fp):>9}  {fmt(tn):>9}  {fmt(fp + tn):>9}")
    print(f"  total        {fmt(tp + fp):>9}  {fmt(fn + tn):>9}  "
          f"{fmt(tp + fn + fp + tn):>9}")
    ppv = tp / (tp + fp)
    print(f"P(condition | +) = {fmt(tp)}/{fmt(tp + fp)} = {ppv} "
          f"= {float(ppv):.3f}")
    print(f"P(+ | condition) = {fmt(tp)}/{fmt(tp + fn)} = "
          f"{float(tp / (tp + fn)):.3f}   (a different question!)")
    print()
    print("Same test, different base rates:")
    print("  base rate   P(condition | +)   P(no condition | -)")
    for rate in ("1/1000", "1/100", "1/10", "1/2"):
        prior = Fraction(rate)
        ppv_r = posterior(prior, sens, 1 - spec)
        npv_r = posterior(1 - prior, spec, 1 - sens)
        print(f"  {float(prior):9.1%}   {float(ppv_r):16.4f}"
              f"   {float(npv_r):19.5f}")
    second = posterior(ppv, sens, 1 - spec)
    print(f"After a second, independent positive test: {float(ppv):.3f} -> "
          f"{float(second):.3f}")
    print()
    match = posterior(Fraction(1, 2_000_000), Fraction(1), Fraction(1, 10**6))
    print("DNA profile shared by 1 person in 1,000,000; city of 2,000,000;")
    print("no other evidence. P(match | innocent) = 0.000001, but")
    print(f"P(innocent | match) = {float(1 - match):.4f}")
    print()
    print("Epistemic status: exact arithmetic in a model whose inputs (base")
    print("rate, sensitivity, specificity, independence of the two tests)")
    print("are assumptions. Change them and the answers change; the")
    print("structure of the calculation (Bayes' theorem) does not.")

if __name__ == "__main__":
    main()
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.

Look at the base-rate table. The test never changes, yet a positive result means anything from a 2%2\% to a 95%95\% chance of having the condition, depending on how common the condition is among the people tested. That is why screening programmes usually follow a positive result with a second, different test — and why a test used on people who already have symptoms (a higher base rate) is more informative than the same test used on everyone.

The last lines are the prosecutor's fallacy. "Only one person in a million has this DNA profile" is P(match∣innocent)P(\text{match} \mid \text{innocent}). But in a city of two million there are about two innocent people who match as well as the guilty one, so, if the match is the only evidence and the suspect was found by searching, P(innocent∣match)P(\text{innocent} \mid \text{match}) is about 23\tfrac23. Real cases have other evidence, which changes the numbers — but the two conditional probabilities must never be confused.

Conditional probability by simulation: dice, doors and cardsPythonStatistical evidenceExact computationComputationally tested
"""Conditional probability as a relative frequency: simulated dice, doors, cards.

A conditional probability P(A | B) can be estimated by looking only at the
trials in which B happened and asking how often A happened too. A seeded
pseudo-random generator rolls two dice 60,000 times: "first die even" is
independent of "total 7", but "first die 6" is not independent of "total at
least 10", and two mutually exclusive events are as dependent as can be. The
Monty Hall game and drawing two cards without replacement show conditioning
changing a probability. Every estimate is printed next to its exact value.
"""

import random
from fractions import Fraction

def roll_pairs(rng, n):
    """n rolls of two fair dice, as (first, second) faces 1..6."""
    return [(rng.randint(1, 6), rng.randint(1, 6)) for _ in range(n)]

def estimate(trials, event, given=None):
    """Relative frequency of `event` among the trials where `given` holds."""
    pool = [t for t in trials if given is None or given(t)]
    return sum(1 for t in pool if event(t)) / len(pool)

def exact(event, given=None):
    """The exact probability over the 36 equally likely outcomes."""
    pool = [(a, b) for a in range(1, 7) for b in range(1, 7)
            if given is None or given((a, b))]
    return Fraction(sum(1 for t in pool if event(t)), len(pool))

def monty_hall(rng, games):
    """Win rates (stick, switch) when the host always opens a goat door."""
    stick = switch = 0
    for _ in range(games):
        car, pick = rng.randrange(3), rng.randrange(3)
        opened = rng.choice([d for d in range(3) if d not in (car, pick)])
        other = next(d for d in range(3) if d not in (pick, opened))
        stick += pick == car
        switch += other == car
    return stick / games, switch / games

def second_ace_given_first(rng, draws):
    """Estimate P(second card is an ace | first is an ace), no replacement."""
    deck = ["A"] * 4 + ["x"] * 48
    both = first = 0
    for _ in range(draws):
        c1, c2 = rng.sample(deck, 2)
        first += c1 == "A"
        both += c1 == "A" and c2 == "A"
    return both / first

def main():
    rng = random.Random(1654)
    rolls = roll_pairs(rng, 60000)
    pairs = [
        ("first even | total 7", lambda t: t[0] % 2 == 0,
         lambda t: t[0] + t[1] == 7),
        ("first is 6 | total >= 10", lambda t: t[0] == 6,
         lambda t: t[0] + t[1] >= 10),
        ("first is 1 | first is 6", lambda t: t[0] == 1, lambda t: t[0] == 6),
    ]
    print("60,000 rolls of two dice      P(A)            P(A | B)")
    print("                              sim    exact    sim    exact")
    for name, a, b in pairs:
        line = (f"  {name:26} {estimate(rolls, a):.3f}  {str(exact(a)):5}    "
                f"{estimate(rolls, a, b):.3f}  {exact(a, b)}")
        print(line)
    print("Independent: P(A | B) = P(A). Not independent: knowing B")
    print("changes the chance of A (to 1/2 in row 2, to 0 in row 3).")
    print()
    stick, switch = monty_hall(rng, 30000)
    print(f"Monty Hall, 30,000 games: stick wins {stick:.3f} (exact 1/3), "
          f"switch {switch:.3f} (2/3)")
    est = second_ace_given_first(rng, 60000)
    print(f"Two cards, 60,000 draws: P(2nd ace | 1st ace) = {est:.3f}")
    print(f"  (exact 3/51 = {3 / 51:.3f}, while P(ace) = 4/52 = "
          f"{4 / 52:.3f})")
    print()
    print("Epistemic status: statistical evidence from one seeded run of a")
    print("pseudo-random generator; another seed gives slightly different")
    print("estimates. The exact values come from counting equally likely")
    print("outcomes, and the lesson proves the rules that connect them.")

if __name__ == "__main__":
    main()
Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.
Explore

Explore: the Monty Hall problem

Stick or switch?

Three doors, one car. After the host opens a door with a goat, should you stick or switch?

0%25%50%75%100%02004006008001,000games playedproportion of wins
  • switch: share of wins so far
  • stick: share of wins so far
  • exact 1/3 and 2/3

Switching wins

Simulated67.5%

Exact2/3 ≈ 66.7%

Sticking wins

Simulated32.5%

Exact1/3 ≈ 33.3%

Simulation of 1,000 games: switching won 67.5%, sticking won 32.5%. The exact values are 2/3 and 1/3.

Play it yourself

Pick a door.

Switching: 0 wins of 0Sticking: 0 wins of 0

Evidence, not proofThis is a simulation of 1,000 games (run 1) using a seeded random number generator. It is evidence, not proof: the exact values come from mathematics, and a new run gives slightly different numbers.

Your first pick is right with probability 1/3. The host always opens a goat door, so switching wins exactly when your first pick was wrong: probability 2/3. In every game exactly one of the two strategies wins.

In a game show there are three doors: a car behind one, goats behind the other two. You pick a door. The host, who knows where the car is, always opens a different door with a goat behind it (choosing at random if there are two), and offers you the chance to switch. Should you? Play a few rounds yourself, then run thousands.

Bayes' theorem explains the answer. Say you picked door 11 and the host opened door 33. Each door hides the car with prior probability 13\tfrac13. If the car is behind door 11, the host opens door 33 with probability 12\tfrac12; if it is behind door 22, he must open door 33 (probability 11); if it is behind door 33, he never opens it. By total probability, P(host opens 3)=13⋅12+13⋅1+13⋅0=12P(\text{host opens } 3) = \tfrac13 \cdot \tfrac12 + \tfrac13 \cdot 1 + \tfrac13 \cdot 0 = \tfrac12, and by Bayes

P(car behind 2∣host opens 3)=1⋅1312=23.P(\text{car behind 2} \mid \text{host opens 3}) = \frac{1 \cdot \tfrac13}{\tfrac12} = \frac23.

Switching wins with probability 23\tfrac23. The host's choice carries information, because it depends on where the car is.

Exercises

Exercises

1. Conditional probability and independence

Warm-upHuman

Two fair dice are rolled and you are told that the total is 99. What is the probability that the first die shows a 55?

Choose one

2. Conditional probability and independence

Warm-upHuman

In the lesson's survey of 400400 students in Hanoi, 200200 cycle to school, 8080 were late at least once, and 3030 cyclists were late. A student is chosen at random from those who were late. What is the probability that they cycle?

Choose one

3. Conditional probability and independence

CoreHuman

A condition affects 2%2\% of a population of 10 00010\,000 people. A test detects it in 90%90\% of people who have it, and gives a false positive for 10%10\% of people who do not. If everyone is tested, how many positive results are expected?

4. Conditional probability and independence

CoreHuman

With the numbers of the previous exercise (base rate 2%2\%, 90%90\% detection, 10%10\% false positives), a randomly chosen person tests positive. About how likely is it that they have the condition?

Choose one

5. Conditional probability and independence

CoreHuman

Two fair dice are rolled. Which pairs of events are independent? (Choose all that apply.)

Choose all that apply

6. Conditional probability and independence

CoreHuman

Events AA and BB are mutually exclusive, with P(A)=0.3P(A) = 0.3 and P(B)=0.4P(B) = 0.4. Which statement is true?

Choose one

7. Conditional probability and independence

CoreHuman

Two cards are drawn from a shuffled pack of 5252 without replacement. The probability that both are aces is 1N\dfrac{1}{N}. What is NN?

8. Conditional probability and independence

StretchHuman

Here is the proof that if AA and BB are independent then so are AA and BcB^c:

P(A∩Bc)=(1)P(A)−P(A∩B)=(2)P(A)−P(A)P(B)=(3)P(A)(1−P(B))=(4)P(A)P(Bc)P(A \cap B^c) \overset{(1)}{=} P(A) - P(A \cap B) \overset{(2)}{=} P(A) - P(A)P(B) \overset{(3)}{=} P(A)\big(1 - P(B)\big) \overset{(4)}{=} P(A)P(B^c).

Which step uses the hypothesis that AA and BB are independent?

Choose one

9. Conditional probability and independence

StretchFormal

In the lesson's Lean model, μ.cond A B is defined as μ.P (A ∩ B) / μ.P B, and Lean's convention makes x / 0 = 0. The lesson proves

theorem bayes (μ : FinProb Ω) (A B : Finset Ω) (hA : μ.P A ≠ 0) : μ.cond A B = μ.cond B A * μ.P A / μ.P B.

What is the role of the hypothesis hA?

Choose one

10. Conditional probability and independence

StretchComputational

Write posterior(prior, sensitivity, false_positive_rate) returning P(D∣positive)P(D \mid \text{positive}) by Bayes' theorem, and after_positives(prior, sensitivity, false_positive_rate, k) returning the probability of DD after kk positive results from independent tests (use each posterior as the next prior). The tests pass Fractions, so keep the arithmetic exact.

Runs entirely in your browser, in an isolated worker. Nothing is sent to a server.
Common misconceptionsH

Common misconceptions

Misconception

Confusing P(A∣B)P(A \mid B) with P(B∣A)P(B \mid A). The probability that a person who has the condition tests positive (95%95\%) is not the probability that a person who tests positive has the condition (about 16%16\%). In court this is the prosecutor's fallacy: "the chance of this evidence if the defendant were innocent is tiny" is not "the chance that the defendant is innocent is tiny". Bayes' theorem converts one into the other, and it needs the base rate.

Misconception

Ignoring base rates. A very accurate test for a very rare condition produces mostly false positives, simply because there are so many more people without the condition. Always ask: "out of how many people, and how many of them had it to begin with?"

Misconception

"Independent means mutually exclusive." Almost the opposite: mutually exclusive events with positive probabilities are never independent (Theorem 8). "First coin heads" and "second coin heads" are independent and can perfectly well happen together.

Misconception

"Independence can always be read off the story." Sometimes it can (separate coins, separate dice), but often it must be checked with numbers. "First die even" and "total even" are independent, which surprises many people; and two events can be dependent through a common cause, like two family members' illnesses. Assuming independence when it fails can turn a large probability into a tiny one — as happened in the case of Sally Clark (see the history section).

ViewpointsH

Other ways of seeing

Geometry— Probability as area

Picture Ω\Omega as a unit square and events as regions, with probability equal to area. Conditioning on BB means zooming in on the region BB and rescaling it to have area 11; P(A∣B)P(A \mid B) is the fraction of BB covered by AA. Two events are independent when they look like a vertical strip and a horizontal strip: the strip {x≤a}\{x \le a\} and the strip {y≤b}\{y \le b\} meet in a rectangle of area abab, exactly the product of their areas. Choosing a random point in the square, "x≤ax \le a" and "y≤by \le b" are independent — the two coordinates do not influence each other.

Algebra— Bayes in odds form

Write probabilities as odds: O(A)=P(A)/P(Ac)O(A) = P(A)/P(A^c). Dividing Bayes' theorem for AA by Bayes' theorem for AcA^c cancels P(B)P(B) and leaves

P(A∣B)P(Ac∣B)⏟posterior odds=P(B∣A)P(B∣Ac)⏟likelihood ratio×P(A)P(Ac)⏟prior odds.\underbrace{\frac{P(A \mid B)}{P(A^c \mid B)}}_{\text{posterior odds}} = \underbrace{\frac{P(B \mid A)}{P(B \mid A^c)}}_{\text{likelihood ratio}} \times \underbrace{\frac{P(A)}{P(A^c)}}_{\text{prior odds}}.

For the screening test the likelihood ratio is 0.95/0.05=190.95 / 0.05 = 19, the prior odds are 1:991 : 99, so the posterior odds are 19:9919 : 99 — the 19/11819/118 we found. Evidence acts by multiplication, and independent pieces of evidence multiply their likelihood ratios; taking logarithms turns this into addition, which is how Alan Turing and I. J. Good scored evidence at Bletchley Park.

Computation— Learning from data

Bayes' theorem is the engine of a large part of modern statistics and machine learning. A spam filter estimates P(spam∣words)P(\text{spam} \mid \text{words}) from the frequencies of words in spam and in ordinary mail; a "naive Bayes" filter simply assumes the words are independent given the class, and works surprisingly well although the assumption is false. In statistical inference, Bayesian methods treat an unknown quantity as uncertain and update a prior distribution into a posterior distribution as data arrive — the screening-test calculation, repeated with many hypotheses at once.

Set-theoretic connectionH

Set-theoretic connection

Every rule in this lesson is a statement about subsets of Ω\Omega. Conditioning on BB replaces the universe Ω\Omega by BB and each event AA by A∩BA \cap B. A partition is a way of cutting Ω\Omega into disjoint pieces — the same notion as the classes of an equivalence relation — and the law of total probability adds the probability of AA up piece by piece. Mutually exclusive means disjoint, a set-theoretic property; independence is a numerical one, which is why the two are so different.

History & global context

History and global context

  • Bayes and Laplace. Thomas Bayes, an English minister, worked out how to reason from observed outcomes back to unknown chances; his essay was published in 1763, after his death, by his friend Richard Price. Pierre-Simon Laplace discovered the theorem independently (1774) and developed it into a general method, applying it, for example, to birth records from Paris and London.
  • Foundations. Andrey Kolmogorov's book of 1933, which set out the axioms of probability used today, defines conditional probability by the ratio P(A∩B)/P(B)P(A \cap B)/P(B) used in this lesson.
  • Codebreaking. During the Second World War, Alan Turing and I. J. Good used Bayes factors — likelihood ratios, added on a logarithmic scale — to weigh evidence when breaking German naval codes at Bletchley Park.
  • Base-rate neglect. In a 1978 study by Ward Casscells, Arno Schoenberger and Thomas Graboys, staff and students at Harvard Medical School were asked about a test with a 5%5\% false-positive rate for a disease affecting 11 person in 10001000. The most common answer for the chance that a person with a positive result has the disease was 95%95\%; fewer than one in five gave the correct answer, about 2%2\%. Gerd Gigerenzer and Ulrich Hoffrage showed in 1995 that people reason far more accurately with natural frequencies than with percentages.
  • A miscarriage of justice. In 1999 Sally Clark, a solicitor in England, was convicted of murdering her two baby sons. An expert witness told the court that the chance of two sudden infant deaths in such a family was about 11 in 7373 million, obtained by squaring the chance of one — assuming the two deaths independent, although shared genetic and environmental factors make that assumption doubtful — and the figure was widely misread as the chance of her innocence. The Royal Statistical Society publicly criticised this use of statistics in 2001, and her convictions were overturned in 2003.
  • Monty Hall. The puzzle was posed by the statistician Steve Selvin in 1975 and became famous in 1990, when Marilyn vos Savant's correct answer — switch — drew thousands of letters insisting she was wrong.
Further reading

Further reading

  • Joseph K. Blitzstein and Jessica Hwang, Introduction to Probability (2014), chapter 2 on conditional probability.
  • Charles M. Grinstead and J. Laurie Snell, Introduction to Probability (1997).
  • Gerd Gigerenzer, Calculated Risks: How to Know When Numbers Deceive You (2002).
  • David Spiegelhalter, The Art of Statistics: Learning from Data (2019).
  • William Feller, An Introduction to Probability Theory and Its Applications, volume 1 (1950), chapter 5 — a classic, for later.