Workbench / Information Theory Companion
B1·03
The Probability You Need
Around chapter 3: how probability connects surprise to entropy and coding; three other ways to see it; what the chapter simplifies (frequencies drift through a file, unseen words are commoner than the counts suggest, and the average wait is not the typical one); how Python's random.choices turns weights into choices with a running total and a binary search, and what a negative weight does to it; four debugging drills; and interview questions.
Understanding it better
Concept map
- Counting (chapter 2) → equally likely cases → probability as a fraction of possibilities.
- Kolmogorov's rules → complements, overlaps, distributions that add to 1.
- Independence → probabilities multiply → surprises add (chapter 1's logarithm).
- Conditional probability → the product rule → Bayes' theorem → conditional surprise (chapter 7).
- Random variables and expected value → expected surprise = entropy (chapter 4) → the average length of a code (chapter 5).
- Law of large numbers → long files behave like their averages → typical sequences and the source coding theorem (chapter 6).
- Binomial → errors in a block of bits (chapters 8 and 9). Geometric → waiting times, runs, retries.
- Estimating from counts → smoothing, never zero → adaptive compressors (chapter 11 and Squeeze).
- Birthday problem → hash and identifier sizes (chapter 10's passwords and hashes).
Explain it differently
Probability as a share of a pie. Draw every possible outcome as a slice of a pie whose whole area is 1. An event is a set of slices; its probability is their area. "Or" for disjoint events adds areas; "given " means throwing away everything outside and blowing up to fill the whole pie, which is why you divide by .
Bayes as a crowd. Picture 100,000 chips walking past an inspector. Most are good, and a small percentage of a huge crowd is still a crowd: 2 % of 99,900 good chips is about 2,000 false flags, beside 99 real ones. Any time Bayes' theorem surprises you, imagine the crowd and count the people.
Expected value as a fair price. If a game pays out the value of a die roll, the fair price to play is 3.5: over many games you'd break even. You'll never win exactly 3.5, but your average winnings settle there. Entropy is the fair price of a symbol in bits: over a long message, that's what each symbol costs to send.
Gaps and misconceptions
What the chapter oversimplifies
1. "A frequency settles to the probability", which assumes the source doesn't change. The law of large numbers needs repetitions under the same conditions. A file isn't always one source:
import re
text = open("data/shakespeare.txt", encoding="utf-8").read().lower()
words = re.findall(r"[a-z]+", text)
tenth = len(words) // 10
for w in ("king", "love", "the"):
rates = [words[i * tenth:(i + 1) * tenth].count(w) / tenth * 1000 for i in range(10)]
print(f"'{w}' per 1000 words, by tenth of the file: " + " ".join(f"{r:5.1f}" for r in rates))
'king' per 1000 words, by tenth of the file: 0.0 3.1 9.8 10.1 0.1 12.2 6.2 1.8 0.0 1.0
'love' per 1000 words, by tenth of the file: 1.2 1.8 1.8 1.5 6.7 2.0 0.8 1.3 1.9 1.9
'the' per 1000 words, by tenth of the file: 37.8 29.8 31.9 31.2 24.5 28.5 32.3 32.0 26.5 27.1
"King" appears 0 times per thousand words in the first tenth of the file and 12.2 in the sixth: the file is a sequence of different plays, and the history plays are full of kings. Even "the" varies from 24.5 to 37.8 per thousand. A single probability for "king", estimated from the whole file, describes no part of it well. Sources whose statistics change are non-stationary, and they're why adaptive compressors, which keep re-estimating as they go and can forget old counts, beat ones that estimate once.
2. "Add one to every count" handles unseen symbols, but how much probability do unseen things deserve? For bytes there are only 256 possibilities. For words, the possibilities are endless, and how many new words to expect is a real question. Alan Turing and I. J. Good answered it at Bletchley Park: the probability that the next item is something never seen before is about the fraction of items seen exactly once.
import re
from collections import Counter
words = re.findall(r"[a-z]+", open("data/shakespeare.txt", encoding="utf-8").read().lower())
half = len(words) // 2
first, second = Counter(words[:half]), words[half:]
new = sum(1 for w in second if w not in first) / len(second)
singletons = sum(1 for w, c in first.items() if c == 1) / half
print(f"first half: {half:,} words, {len(first):,} different, {sum(1 for c in first.values() if c == 1):,} seen exactly once")
print(f"fraction of second-half words never seen in the first half: {new:.4f}")
print(f"Good-Turing estimate from the first half alone (once-seen words / all words): {singletons:.4f}")
first half: 104,251 words, 7,979 different, 3,697 seen exactly once
fraction of second-half words never seen in the first half: 0.0783
Good-Turing estimate from the first half alone (once-seen words / all words): 0.0355
From the first half alone, the Good–Turing estimate says about 3.6 % of upcoming words should be new. In fact 7.8 % of the second half's words never appeared in the first half: more than twice the estimate, because the second half is different plays with different characters and subjects (point 1 again). Good–Turing is exact in expectation only for a source that doesn't change. Both numbers dwarf what add-one smoothing would give unseen words, which is why language models and compressors set aside probability for "something new" explicitly rather than by adding small counts to a vocabulary they can't list.
3. "The expected value is the long-run average", which isn't what usually happens. Chapter 3 says you wait 6 rolls on average for a six. Measured:
import random, statistics
random.seed(6)
waits = []
for _ in range(100_000):
t = 1
while random.randint(1, 6) != 6:
t += 1
waits.append(t)
print(f"waiting for a six, 100,000 times: mean {statistics.mean(waits):.2f}, median {statistics.median(waits)}, "
f"most common {statistics.mode(waits)}, longest {max(waits)}")
print("share of waits longer than the mean:", round(sum(w > 6 for w in waits) / len(waits), 3))
waiting for a six, 100,000 times: mean 6.00, median 4.0, most common 1, longest 71
share of waits longer than the mean: 0.335
The mean wait is 6.00, as promised; but the median is 4, the single most common wait is 1, and the longest of 100,000 waits was 71 rolls. A third of waits are longer than the mean. Skewed distributions (waiting times, file sizes, word frequencies, incomes) have means pulled up by rare long values, so "expected" describes totals over many trials, not a typical trial. For information that matters: a code's average length can be excellent while some messages come out long, and buffers and timeouts have to be sized for the tail, not the mean.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "A word's frequency in a file is its probability." | Frequencies drift through a file: "king" from 0 to 12 per thousand words. | What the chapter oversimplifies, point 1 |
| "Unseen things are rare enough to ignore." | 7.8 % of the second half's words were absent from the first half. | What the chapter oversimplifies, point 2 |
| "The expected wait is the typical wait." | Mean 6, median 4, most common 1, longest 71. | What the chapter oversimplifies, point 3 |
| "Weighted random choice checks its weights." | random.choices accepts a negative weight and silently never picks some items. |
Code walkthrough |
| "Probabilities that should add to 1 will compare equal to 1.0." | Ten 0.1s added in a loop give 0.9999999999999999. | Drill D1 |
| "P(h after t) is count(th) ÷ count(h)." | It's count(th) ÷ count(t followed by anything). | Drill D2 |
| "Two servers fail together with the product of their chances." | Only if independent; a shared cause makes it 23 times likelier. | Drill D3 |
| "A million random ids are plenty for 5,000 users." | About 12 collisions are expected; the test failed every time. | Drill D4 |
Theoretical gaps: the ideas behind the chapter
- Stationarity and ergodicity. A source is stationary if its statistics don't change over time, and ergodic if one long sample shows all of them. Shannon's theorems are proved for stationary ergodic sources; real files only approximate them (point 1), which is why practical compressors adapt.
- Good–Turing estimation. For a symbol seen times, Good (1953, crediting Turing) estimated its probability as , where is the number of symbols seen exactly times. It underlies smoothing in language models and estimates of "how many species haven't we seen yet" in ecology.
- Concentration inequalities. The law of large numbers says averages settle; Chernoff and Hoeffding bounds say how fast, exponentially in the number of samples. They're the tool behind modern proofs of the coding theorems and behind the sample sizes in randomised algorithms.
Applying it
Code walkthrough
random.choices picks items with given probabilities, the operation every simulation in this book uses to generate text from a model. Excerpt from Lib/random.py in Python 3.13 (on your computer: python3 -c "import random; print(random.__file__)"):
def choices(self, population, weights=None, *, cum_weights=None, k=1):
"""Return a k sized list of population elements chosen with replacement.
...
"""
random = self.random
n = len(population)
if cum_weights is None:
if weights is None:
floor = _floor
n += 0.0 # convert to float for a small speed improvement
return [population[floor(random() * n)] for i in _repeat(None, k)]
try:
cum_weights = list(_accumulate(weights))
...
total = cum_weights[-1] + 0.0 # convert to float
if total <= 0.0:
raise ValueError('Total of weights must be greater than zero')
if not _isfinite(total):
raise ValueError('Total of weights must be finite')
bisect = _bisect
hi = n - 1
return [population[bisect(cum_weights, random() * total, 0, hi)]
for i in _repeat(None, k)]
The method lays the probabilities end to end on a line: _accumulate turns weights 12, 9, 8, 7 into running totals 12, 21, 29, 36, so item owns the stretch between total and total , of length proportional to its weight. random() * total picks a uniformly random point on the line from 0 to 36, and bisect finds, by binary search (chapter 1's halving questions), which stretch contains it. Each item is chosen with probability equal to its share of the line: the sum rule for disjoint events, made physical. A weight of 0 gives a stretch of length 0, which is never hit. Chapter 6's arithmetic coding uses exactly this picture in reverse: a message is coded by which stretch of the line it falls in. Measured:
import random
from collections import Counter
random.seed(9)
letters, weights = "etaoz", [12, 9, 8, 7, 0]
draws = Counter(random.choices(letters, weights=weights, k=360_000))
print("weights", dict(zip(letters, weights)), "-> frequencies", {c: round(draws[c] / 360_000, 4) for c in letters})
print("expected:", {c: round(w / sum(weights), 4) for c, w in zip(letters, weights)})
print("a negative weight is not rejected:", Counter(random.choices("abc", weights=[1, -1, 1], k=10_000)))
weights {'e': 12, 't': 9, 'a': 8, 'o': 7, 'z': 0} -> frequencies {'e': 0.3326, 't': 0.2512, 'a': 0.2215, 'o': 0.1947, 'z': 0.0}
expected: {'e': 0.3333, 't': 0.25, 'a': 0.2222, 'o': 0.1944, 'z': 0.0}
a negative weight is not rejected: Counter({'c': 10000})
With 360,000 draws, every frequency is within 0.001 of its weight's share, and the weight-0 letter never appears. The last line is the surprise: weights 1, −1, 1 aren't rejected (the code checks only that the total is positive and finite), and the running totals 1, 0, 1 are no longer increasing, so the binary search misbehaves: "a", with weight 1, is never chosen, and every draw is "c".
Read it yourself
Using the code above, explain why choices("abc", weights=[1, -1, 1]) always returns "c". Then say what check would catch it, and why a library might choose not to make it.
Debugging drills
D1. A distribution that doesn't add up
A model loader checks that each distribution's probabilities add up to exactly 1, and rejects one of three perfectly good distributions.
def check_distribution(probs):
total = 0.0
for p in probs:
if p < 0:
raise ValueError("negative probability")
total += p
if total != 1.0:
raise ValueError(f"probabilities add up to {total!r}, not 1")
return True
for name, probs in (("halves", [0.5, 0.5]), ("tenths", [0.1] * 10), ("fifths", [0.2] * 5)):
try:
print(name, check_distribution(probs))
except ValueError as e:
print(name, "rejected:", e)
halves True
tenths rejected: probabilities add up to 0.9999999999999999, not 1
fifths True
D2. Conditional probabilities that add up to 1.76
A function for "the probability that letter follows letter " gives P(h | t) = 0.51 and P(u | q) = 0.03, and its values for all letters after "t" add up to 1.76.
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")
pairs = Counter(zip(letters, letters[1:]))
single = Counter(letters)
def p_given(b, a):
"""P(next letter is b | this letter is a)."""
return pairs[(a, b)] / single[b]
print("P(h | t) =", round(p_given("h", "t"), 4))
print("P(u | q) =", round(p_given("u", "q"), 4))
print("sum over all next letters after 't':", round(sum(p_given(b, "t") for b in single), 4))
P(h | t) = 0.5052
P(u | q) = 0.0281
sum over all next letters after 't': 1.7587
D3. Two replicas that fail together far too often
A capacity plan says two database replicas will both be down on 0.02 % of days, multiplying each one's 1.5 % chance. A year of incidents says otherwise.
import random
random.seed(10)
p_fail, p_shared = 0.01, 0.005 # each server's own failures, and a shared power cut that takes both down
days = 1_000_000
both = 0
for _ in range(days):
shared = random.random() < p_shared
a = shared or random.random() < p_fail
b = shared or random.random() < p_fail
both += a and b
p_each = 1 - (1 - p_fail) * (1 - p_shared)
print(f"each server down on {p_each:.4f} of days")
print(f"report: both down on {p_each * p_each:.6f} of days (product of the two)")
print(f"simulated: both down on {both / days:.6f} of days")
each server down on 0.0150 of days
report: both down on 0.000224 of days (product of the two)
simulated: both down on 0.005133 of days
D4. A uniqueness test that always fails
A test creates 5,000 user ids with random.randint(0, 10**6) and asserts they're unique. It fails on every run, though "a million is far more than 5,000".
import random
def make_ids(n):
return [random.randint(0, 10 ** 6) for _ in range(n)]
failures = 0
for run in range(1000):
random.seed(run)
ids = make_ids(5000)
failures += len(set(ids)) < len(ids)
print(f"test 'ids are unique' failed in {failures} of 1000 runs")
random.seed(0)
ids = make_ids(5000)
print("duplicates in one run:", len(ids) - len(set(ids)), "(expected pairs: n²/2M =", round(5000 ** 2 / (2 * (10 ** 6 + 1)), 1), ")")
test 'ids are unique' failed in 1000 of 1000 runs
duplicates in one run: 14 (expected pairs: n²/2M = 12.5 )
Career-oriented
Interview prep
Mid level
Q1. Explain Bayes' theorem with an example where the answer surprises people.
How to get there. A rare condition, an imperfect test, and a crowd.
Q2. You need ids for 10 million records and want to generate them randomly without coordination. How many bits do you need?
How to get there. The birthday bound.
Senior level
Q3. A compression library estimates symbol probabilities from counts. A bug report says it crashes on files containing a byte value it had never seen in the first block. What's the likely cause and the fix?
How to get there. Zero-frequency problem.
Q4. Two independent services each have 99.9 % availability, and a request needs both. A second design puts a cache in front so 90 % of requests need only the first service. Compare.
How to get there. Multiply for "both needed", condition on the request type.
Staff level
Q5. Your company's anomaly detector pages engineers about 20 times a week, and only one page in fifteen is a real incident. Leadership asks you to fix the on-call experience without missing incidents. How do you reason about it?
How to get there. Base rates, precision against recall, and independence of signals.
Q6. A team reports that an experiment raised conversion by 3 % "with 95 % confidence" after checking the dashboard every day and stopping when it crossed the line. What do you say?
How to get there. Repeated looks, and the law.