IT·03
The Probability You Need
Just enough probability for the rest of the book, built from counting: outcomes, events and the rules every probability obeys; why independent probabilities multiply; conditional probability and Bayes' theorem; random variables, averages and the law of large numbers; the binomial and geometric distributions; estimating probabilities from counts without ever assigning zero; and the birthday problem, measured on dice, letter pairs in Shakespeare, birthdays and random identifiers.
Start here
What this chapter answers
What exactly is a probability, and what rules must every probability obey? Why do independent probabilities multiply, the fact chapter 1 used to show surprise must be a logarithm? How does knowing one thing change the probability of another? What does "on average" mean precisely, and why do frequencies settle down? How do you estimate a probability from data without making a mistake that breaks a compressor? And why do random identifiers collide much sooner than intuition says?
Probability in one picture
Roll a fair die a million times and count the sixes. After 10 rolls the fraction of sixes might be 0.1 or 0.3; after a million it's very close to . The probability is the number the fraction settles to, and it's also what you get by counting: one face out of six equally likely faces. Every probability in this book comes from one of those two places, counting equally likely cases or measuring long-run frequencies, and the rules below hold for both.
Outcomes, events and probabilities
The rules
An experiment has a set of possible outcomes (a die: 1 to 6). An event is a set of outcomes ("even": 2, 4 or 6). A probability assigns each event a number obeying three rules, Kolmogorov's axioms in plain words:
- Every probability is between 0 and 1: .
- Something happens: the event "any outcome at all" has probability 1.
- For events that can't happen together (disjoint events), probabilities add: .
Everything else follows. The complement of , "not ", has , since and "not " are disjoint and together certain. When events can overlap, the overlap is counted twice, so
When all outcomes are equally likely, each has probability and an event's probability is a count: . That's where chapter 2's counting comes in: the chance that a 5-card hand is all hearts is .
Distributions
When outcomes are named by values (a die's face, a letter, a byte), listing each value's probability gives the probability distribution. A distribution's probabilities are non-negative and add up to 1. A uniform distribution gives every value the same probability; chapter 1's letter frequencies, from down to , are a distribution that's far from uniform. In this book a source is described by such a distribution: the probabilities of the symbols it might produce.
Combining events
Independence: why probabilities multiply
Two events are independent if knowing whether one happened tells you nothing about the other. Then the probability that both happen is the product:
The counting picture explains it. Roll two dice: there are equally likely pairs (chapter 2's multiplication principle). "First die is six" holds in 6 of them and "second die is six" in 6, and "both are six" in exactly 1: . In general, if happens in a fraction of cases, and among those happens in the same fraction as everywhere else, then both happen in a fraction . That's the fact chapter 1 used: independent probabilities multiply, so their surprises, being logarithms, add.
Independence is a property of the world, not of the arithmetic, and it often fails. In Shakespeare's plays, the pair "th" occurs almost six times as often as the product of the frequencies of "t" and "h" would predict, and "qu" 28 times as often (the lab measures them): letters aren't independent of their neighbours. That dependence is exactly the redundancy that compressors exploit.
Conditional probability
The probability of given that happened is written : restrict attention to the cases where happened, and ask what fraction of those also have :
Rearranged, it's the product rule, which holds whether or not the events are independent:
Independence is the special case . In the plays, , but : knowing the last letter changes the odds a lot. In bits, an "h" after a "t" carries bits instead of . Chapter 7 builds a whole theory on this.
Bayes' theorem
The product rule can be written two ways, , and dividing gives
It turns "how likely is the evidence if the cause is true?" into "how likely is the cause, given the evidence?", and the answer can be startlingly different. A factory tests chips: 1 in 1000 is faulty; the test flags 99 % of faulty chips, and also, wrongly, 2 % of good ones. A chip is flagged. How likely is it to be faulty?
Random variables and averages
Expected value
A random variable is a number that depends on the outcome: the face of a die, the number of heads in 10 tosses, the surprise of a letter. Its expected value (or mean) is the average of its values, each weighted by its probability:
adding over every value that can take.
A fair die has , a value the die never shows: the expectation is a long-run average, not a typical outcome. Expected values add, , always, even for dependent variables, which makes them easy to work with. The most important random variable in this book is surprise itself: if a source produces symbol with probability , the surprise is a random variable, and its expected value is the source's entropy, chapter 4's subject.
The spread around the mean is measured by the variance, , the average squared distance from the mean; its square root is the standard deviation. For independent variables, variances add too.
The law of large numbers
It's why probabilities can be measured as frequencies, and why averages over long messages are what information theory talks about: a compressor's performance on a long file is close to its expected performance, even though any single symbol might be surprising. How fast the average settles is set by the variance: the typical distance of an average of copies from the mean shrinks like . Ten thousand rolls pin the frequency of sixes to within about ; a million to within .
Two distributions that come up everywhere
Binomial. In independent trials, each succeeding with probability , the number of successes has
choices of which trials succeed (chapter 2), each with probability (independence). Its mean is and its variance . It counts heads in coin tosses, errors in a block of transmitted bits (chapter 8), and the number of "e"s in 100 letters of text, which the lab compares with real windows of the plays.
Geometric. The number of trials up to and including the first success has , with mean : you wait on average 6 rolls for a six. It describes runs of identical symbols, gaps between rare events, and retries in chapter 2's rejection sampling (the companion's randbelow).
Estimating probabilities from data
Frequencies, and the zero problem
A compressor can't be told the true probabilities of the symbols in a file; it has to estimate them, usually by counting. If symbol appeared times in , the natural estimate is . For common symbols in long files that's excellent (the law of large numbers). For rare symbols it's dangerous: a symbol never seen gets , and its surprise is . A code built from those estimates has no codeword for it, and when it finally turns up, the compressor fails.
The standard fix goes back to Laplace. His rule of succession (1814) estimates the probability that the sun rises tomorrow, after seeing it rise times out of , as , never quite 1. Its general form, add-one smoothing, pretends every symbol was seen once more than it was:
for an alphabet of symbols. Every symbol gets a probability above zero, and as grows the extra 1s stop mattering. Real compressors use refinements (adding instead of 1, the Krichevsky–Trofimov estimator, or reserving probability for "a new symbol" as PPM compressors do), but every one of them obeys the same rule: never give a possible symbol zero probability.
The birthday problem
How many people must be in a room for it to be more likely than not that two share a birthday? Treat birthdays as independent and uniform over 365 days. The chance that people all have different birthdays is a product (each person must avoid the days already taken):
At it drops below : 23 people are enough. The reason is that collisions can happen between any pair, and people make pairs (253 for 23 people), each colliding with probability . The expected number of colliding pairs is about for possible values, and a good approximation for the chance of at least one collision is
So collisions become likely once reaches about , not . For random identifiers of bits, , and collisions become likely after about ids: 77,000 for 32-bit ids, 5 billion for 64-bit, which is why chapter 1's exercises found 64-bit random ids too short for 10 billion orders, and why random UUIDs use 122 random bits. The same calculation sets the size of hashes used to detect duplicate files and the security of digital signatures against "birthday attacks".
Lab: probability measured
Experiment 1: frequencies settle down
import random
random.seed(1654)
rolls = [random.randint(1, 6) for _ in range(1_000_000)]
for n in (10, 100, 1_000, 10_000, 100_000, 1_000_000):
sixes = rolls[:n].count(6)
print(f"after {n:>9,} rolls: {sixes:>7,} sixes, frequency {sixes / n:.4f} (probability {1 / 6:.4f})")
after 10 rolls: 1 sixes, frequency 0.1000 (probability 0.1667)
after 100 rolls: 20 sixes, frequency 0.2000 (probability 0.1667)
after 1,000 rolls: 170 sixes, frequency 0.1700 (probability 0.1667)
after 10,000 rolls: 1,644 sixes, frequency 0.1644 (probability 0.1667)
after 100,000 rolls: 16,877 sixes, frequency 0.1688 (probability 0.1667)
after 1,000,000 rolls: 166,987 sixes, frequency 0.1670 (probability 0.1667)
After 10 rolls the frequency of sixes is 0.1; after 100 it's 0.2: small samples wander a long way from . By a million rolls it's 0.1670, within 0.0004 of 0.1667, about the scale the law of large numbers predicts. (These are pseudo-random rolls from a fixed seed, so your run matches exactly.)
Experiment 2: letters are not independent
from collections import Counter
text = open("data/shakespeare.txt", encoding="utf-8").read().lower()
letters = "".join(c for c in text if "a" <= c <= "z")
n = len(letters)
single = Counter(letters)
pairs = Counter(letters[i:i + 2] for i in range(n - 1))
P = lambda c: single[c] / n
P2 = lambda ab: pairs[ab] / (n - 1)
for ab in ("th", "he", "qu", "ht", "zz"):
a, b = ab
print(f"P({ab}) = {P2(ab):.5f} P({a}) x P({b}) = {P(a) * P(b):.5f} ratio {P2(ab) / (P(a) * P(b)):6.2f}")
print(f"\nP(h) = {P('h'):.4f} P(h | previous letter t) = {pairs['th'] / sum(v for k, v in pairs.items() if k[0] == 't'):.4f}")
print(f"P(e) = {P('e'):.4f} P(e | previous letter t) = {pairs['te'] / sum(v for k, v in pairs.items() if k[0] == 't'):.4f}")
P(th) = 0.03228 P(t) x P(h) = 0.00556 ratio 5.81
P(he) = 0.02273 P(h) x P(e) = 0.00756 ratio 3.01
P(qu) = 0.00099 P(q) x P(u) = 0.00003 ratio 28.47
P(ht) = 0.00287 P(h) x P(t) = 0.00556 ratio 0.52
P(zz) = 0.00001 P(z) x P(z) = 0.00000 ratio 30.50
P(h) = 0.0639 P(h | previous letter t) = 0.3711
P(e) = 0.1183 P(e | previous letter t) = 0.0715
If letters were independent, each ratio would be close to 1. Instead "th" is 5.8 times more common than independence predicts, "he" 3 times, "qu" 28 times, while "ht" is half as common. The conditional probabilities show the same thing from the other side: an "h" is almost six times likelier straight after a "t" (0.371) than in general (0.064), and an "e" is less likely after a "t" (0.072 against 0.118). Every one of these departures from independence is information a context-aware compressor can use and a letter-by-letter one can't.
Experiment 3: the birthday problem, exactly and by simulation
import math, random
def p_shared(n, days=365):
"""Exact probability that at least two of n people share a birthday."""
p_all_different = 1.0
for i in range(n):
p_all_different *= (days - i) / days
return 1 - p_all_different
random.seed(23)
for n in (10, 23, 50, 70):
sims = sum(len(set(random.randrange(365) for _ in range(n))) < n for _ in range(20_000)) / 20_000
print(f"{n:>3} people: exact {p_shared(n):.4f} simulated {sims:.4f} approximation 1 - e^(-n²/2M) = {1 - math.exp(-n * n / (2 * 365)):.4f}")
for bits in (32, 64, 122):
m = 2 ** bits
n_half = math.sqrt(2 * m * math.log(2))
print(f"random {bits:>3}-bit ids: a 50 % chance of some collision after about {n_half:.3g} ids")
10 people: exact 0.1169 simulated 0.1134 approximation 1 - e^(-n²/2M) = 0.1280
23 people: exact 0.5073 simulated 0.5165 approximation 1 - e^(-n²/2M) = 0.5155
50 people: exact 0.9704 simulated 0.9684 approximation 1 - e^(-n²/2M) = 0.9674
70 people: exact 0.9992 simulated 0.9993 approximation 1 - e^(-n²/2M) = 0.9988
random 32-bit ids: a 50 % chance of some collision after about 7.72e+04 ids
random 64-bit ids: a 50 % chance of some collision after about 5.06e+09 ids
random 122-bit ids: a 50 % chance of some collision after about 2.71e+18 ids
With 23 people the exact chance of a shared birthday is 0.507, and 20,000 simulated rooms agree to within 0.01. The approximation is good everywhere. For random identifiers, a 50 % chance of a collision arrives after about ids: 77,200 for 32 bits, 5 billion for 64, and for the 122 random bits of a version-4 UUID, enough that a collision among all the UUIDs anyone will ever generate is very unlikely.
Experiment 4: counting e in windows of text
import math
from collections import Counter
text = open("data/shakespeare.txt", encoding="utf-8").read().lower()
letters = "".join(c for c in text if "a" <= c <= "z")
p = letters.count("e") / len(letters)
w = 100
windows = [letters[i:i + w].count("e") for i in range(0, len(letters) - w, w)]
seen = Counter(windows)
mean = sum(windows) / len(windows)
var = sum((k - mean) ** 2 for k in windows) / len(windows)
print(f"{len(windows):,} windows of {w} letters; P(e) = {p:.4f}")
print(f"mean count of e: {mean:.2f} (binomial predicts {w * p:.2f}); variance {var:.2f} (binomial predicts {w * p * (1 - p):.2f})")
print(" k observed binomial")
for k in range(4, 21, 2):
pred = math.comb(w, k) * p ** k * (1 - p) ** (w - k) * len(windows)
print(f"{k:>2} {seen[k]:>10,} {pred:>10,.0f}")
8,510 windows of 100 letters; P(e) = 0.1183
mean count of e: 11.83 (binomial predicts 11.83); variance 9.83 (binomial predicts 10.43)
k observed binomial
4 39 37
6 188 202
8 549 567
10 977 949
12 1,022 1,036
14 784 784
16 425 430
18 167 176
20 47 55
Cut the plays' letters into 8,510 windows of 100 and count the "e"s in each. If letters were independent draws with , the counts would follow the binomial distribution with . The mean matches exactly (it must: it's the same frequency), and the shape is close at every count. The variance is a little smaller than predicted (9.83 against 10.43): real text spreads its "e"s more evenly than independent draws would, because words have structure (vowels and consonants tend to alternate, so "e"s rarely bunch up). Independence is a good first model of text and a wrong final one.
Worked examples
Rules and complements
Expected values and surprise
Smoothing
Exercises
Practice
- A card is drawn from a shuffled deck. Find the probability that it's: a heart; a king; a heart or a king; not a face card (jack, queen, king).
- Three fair coins are tossed. What's the probability of exactly two heads? Of at least one head?
- A bag holds 3 red and 2 blue balls. Two are drawn without replacing the first. What's the probability both are red? Are the two draws independent?
- What's the expected value of the number of heads in 10 tosses of a fair coin? The variance?
- A test for a rare condition affecting 1 in 500 is 95 % sensitive (flags 95 % of real cases) and flags 1 % of others. What fraction of flagged cases are real?
- How many rolls of a die do you expect to wait for a six? For a double six with two dice?
- With 1,000 random 32-bit ids, estimate the expected number of colliding pairs.
Answers
- ; ; ; .
- ; .
- . Not independent: the second draw's chances depend on the first.
- Mean ; variance .
- Real and flagged: ; false alarms ; so .
- 6 rolls; 36 rolls (a double six has probability ).
- .
Harder
- Prove that if and are independent, so are and "not ".
- Show that if and only if (for events with non-zero probability). Why is independence therefore symmetric?
- Explain why even when and are dependent, using a table of joint probabilities.
- A compressor estimates byte probabilities from the first 1,000 bytes of a file and then codes the whole file with them. Describe two ways this can go wrong, and one fix for each.
- How many random 64-bit ids can a system create before the chance of any collision reaches 1 in a million? (Use for small .)
Answers
- .
- Both say : divide by for the first, by for the second. So independence is a property of the pair, not a direction.
- . Summing over gives , so the first sum is , and likewise the second is . No independence was used.
- A byte that doesn't appear in the first 1,000 gets probability 0 and can't be coded later (fix: smoothing, or an escape code for new symbols). And the file's statistics may change part way through, such as text followed by a table (fix: adaptive estimates, updated as the file is coded, which chapter 11 and the capstone's final stage use).
- Need , so : about six million ids.
Challenge
- In the "Monty Hall" game, a prize is behind one of three doors. You pick a door; the host, who knows where the prize is, opens another door with no prize, and offers to let you switch. Use conditional probability to show that switching wins with probability . Then explain, in terms of information, what the host's choice told you.
Discussion
Say you pick door 1. The prize is behind 1, 2 or 3, each with probability . If it's behind 1, the host opens 2 or 3 at random and switching loses. If it's behind 2, the host must open 3, and switching to 2 wins; if behind 3, the host must open 2, and switching wins. So switching wins in 2 of the 3 equally likely cases: . By Bayes: given the host opened door 3, and . In information terms, the host's choice isn't random when the prize is behind door 2 or 3: it's forced, so which door he opens carries information about where the prize is (his opening tells you nothing about your own door, which he was never allowed to open). The surprise of "he opened door 3" is 1 bit, and it shifts the odds of door 2 from to . Chapter 7's mutual information measures how much one observation tells about another.
In real life
Misconceptions and limits
The model to keep
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "After a run of sixes, a six is less likely." | Independent rolls have no memory; each is still . | Independence: why probabilities multiply |
| "Frequencies match probabilities in any sample." | Small samples wander: 20 sixes in 100 rolls happened in the lab. | Experiment 1 |
| "Letters in text are independent." | "th" occurs 5.8 times as often as independence predicts. | Experiment 2 |
| "An accurate test's positive result is probably right." | For rare conditions most positives can be false alarms (4.7 % in the chip example). | Bayes' theorem |
| "P(A given B) is about the same as P(B given A)." | They can differ hugely; Bayes' theorem connects them through and . | Bayes' theorem |
| "A symbol never seen has probability zero." | It has an unknown small probability; zero breaks compressors. | Frequencies, and the zero problem |
| "You need about 183 people for a shared birthday to be likely." | 23 are enough: there are 253 pairs. | The birthday problem |
| "The expected value is the most likely value." | A die's expectation, 3.5, never comes up. | Expected value |
Limits and trade-offs
- Where do the probabilities come from? The rules say how probabilities combine, not what they are. Counting equally likely cases, measuring frequencies and expressing degrees of belief are three interpretations, argued over by philosophers since Laplace; information theory works with any of them, as long as the same probabilities are used throughout.
- Independence is usually an approximation. Real data (text, images, network traffic) is full of dependence; models that assume independence are simple and wrong in ways the lab can measure.
- This is only the probability the book needs. Continuous distributions (probabilities spread over real numbers, like a normal curve) appear only briefly in chapters 8 and 9; the Mathematics shelf's Probability book covers them fully.
Revision sheet
Key ideas
- Rules: ; certain = 1; disjoint events add. Complement: . Overlap: .
- Equally likely: probability = favourable count ÷ total count.
- Independent: , so surprises add.
- Conditional: ; product rule .
- Bayes: ; rare causes stay rare after weak evidence.
- Expected value ; always additive. Variance .
- Law of large numbers: averages approach expectations; error shrinks like .
- Binomial: , mean . Geometric: wait on average.
- Estimating: (add-one); never zero.
- Birthday: collisions likely after about values; expected pairs .
Glossary
- Possible outcome: one possible result of an experiment, such as a die showing 4.
- Random event: a set of possible outcomes, such as "the die shows an even number", whose probability can be asked about.
- Probability: a number from 0 to 1 assigned to each event, following Kolmogorov's rules.
- Probability distribution: the list of probabilities of each value a random quantity can take; non-negative and adding to 1.
- Independent events: events where knowing one happened doesn't change the probability of the other; their probabilities multiply.
- Conditional probability: , the probability of among the cases where happened.
- Bayes' theorem: , reversing a conditional probability.
- Random variable: a number whose value depends on the outcome of an experiment.
- Expected value: the probability-weighted average of a random variable's values; its long-run average.
- Variance: the expected squared distance of a random variable from its mean.
- Law of large numbers: averages of many independent repetitions approach the expected value.
- Binomial distribution: the distribution of the number of successes in independent trials with the same success probability.
- Geometric distribution: the distribution of the number of trials up to the first success.
- Add-one smoothing: estimating a probability as so that no symbol gets probability zero; Laplace's rule of succession.
- Birthday problem: the fact that among random values from , a repeat becomes likely once is about .