Information TheoryComputer Science, Applied · Book 1
0 / 0

Shelves / Information Theory

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.

28 topics · ~30 min read · 13-question quiz
Updated Suggest a correction

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 16≈0.1667. The probability 16 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 P(A) obeying three rules, Kolmogorov's axioms in plain words:

  1. Every probability is between 0 and 1: 0≤P(A)≤1.
  2. Something happens: the event "any outcome at all" has probability 1.
  3. For events that can't happen together (disjoint events), probabilities add: P(A or B) =P(A)+P(B).

Everything else follows. The complement of A, "not A", has P(not A)=1−P(A), since A and "not A" are disjoint and together certain. When events can overlap, the overlap is counted twice, so

P(A or B)=P(A)+P(B)−P(A and B).

When all N outcomes are equally likely, each has probability 1N and an event's probability is a count: P(A) =outcomes in AN. That's where chapter 2's counting comes in: the chance that a 5-card hand is all hearts is (135)/(525) =1287/2,598,960≈0.000495.

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 P(e)=0.118 down to P(z)=0.00065, 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:

P(A and B)=P(A)×P(B).

The counting picture explains it. Roll two dice: there are 6×6=36 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: 136 =16×16. In general, if A happens in a fraction P(A) of cases, and among those B happens in the same fraction P(B) as everywhere else, then both happen in a fraction P(A)×P(B). 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 B given that A happened is written P(B∣A): restrict attention to the cases where A happened, and ask what fraction of those also have B:

P(B∣A)=P(A and B)P(A).

Rearranged, it's the product rule, which holds whether or not the events are independent:

P(A and B)=P(A)×P(B∣A).

Independence is the special case P(B∣A)=P(B). In the plays, P(h)≈0.064, but P(h∣previous letter is t)≈0.371: knowing the last letter changes the odds a lot. In bits, an "h" after a "t" carries −log20.371≈1.43 bits instead of −log20.064≈3.97. Chapter 7 builds a whole theory on this.

Bayes' theorem

The product rule can be written two ways, P(A)P(B∣A) =P(B)P(A∣B), and dividing gives

Interactive diagram: Bayes' theorem as a crowd of 100,000 chips. It needs JavaScript; the text around it says the same.

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:

E[X]=∑kkP(X=k),

adding over every value k that X can take.

A fair die has E[X] =1+2+3+4+5+66 =3.5, a value the die never shows: the expectation is a long-run average, not a typical outcome. Expected values add, E[X+Y]=E[X]+E[Y], 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 x with probability p(x), the surprise −log2p(x) 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, Var(X) =E[(X−E[X])2], 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 n copies from the mean shrinks like 1n. Ten thousand rolls pin the frequency of sixes to within about ±0.004; a million to within ±0.0004.

Two distributions that come up everywhere

Binomial. In n independent trials, each succeeding with probability p, the number of successes K has

P(K=k)=(nk)pk(1−p)n−k:

(nk) choices of which trials succeed (chapter 2), each with probability pk(1−p)n−k (independence). Its mean is np and its variance np(1−p). 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 P(T=t)=(1−p)t−1p, with mean 1p: 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 x appeared cx times in n, the natural estimate is p^(x)=cxn. 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 p^=0, and its surprise is −log20=∞. 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 n times out of n, as n+1n+2, never quite 1. Its general form, add-one smoothing, pretends every symbol was seen once more than it was:

p^(x)=cx+1n+K

for an alphabet of K symbols. Every symbol gets a probability above zero, and as n grows the extra 1s stop mattering. Real compressors use refinements (adding 12 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 n people all have different birthdays is a product (each person must avoid the days already taken):

Interactive diagram: The birthday problem: count the pairs. It needs JavaScript; the text around it says the same.
P(all different)=365365×364365×⋯×365−n+1365.

At n=23 it drops below 12: 23 people are enough. The reason is that collisions can happen between any pair, and n people make (n2) =n(n−1)2 pairs (253 for 23 people), each colliding with probability 1365. The expected number of colliding pairs is about n22M for M possible values, and a good approximation for the chance of at least one collision is

P(some collision)≈1−e−n2/2M.

So collisions become likely once n reaches about M, not M. For random identifiers of b bits, M=2b, and collisions become likely after about 2b/2 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

Python
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})")
Text
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 16. By a million rolls it's 0.1670, within 0.0004 of 0.1667, about the 1n 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

Python
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}")
Text
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

Python
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")
Text
 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 1−e−n2/2M is good everywhere. For random identifiers, a 50 % chance of a collision arrives after about 1.18M ids: 77,200 for 32 bits, 5 billion for 64, and 2.7×1018 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

Python
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}")
Text
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 P(e)=0.1183, the counts would follow the binomial distribution with n=100. 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

  1. 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).
  2. Three fair coins are tossed. What's the probability of exactly two heads? Of at least one head?
  3. 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?
  4. What's the expected value of the number of heads in 10 tosses of a fair coin? The variance?
  5. 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?
  6. How many rolls of a die do you expect to wait for a six? For a double six with two dice?
  7. With 1,000 random 32-bit ids, estimate the expected number of colliding pairs.
Answers
  1. 14; 113; 13+4−152 =1652 =413; 1−1252 =4052 =1013.
  2. (32/)8=38; 1−18=78.
  3. 35×24 =310. Not independent: the second draw's chances depend on the first.
  4. Mean 10×12=5; variance 10×12×12 =2.5.
  5. Real and flagged: 0.002×0.95=0.0019; false alarms 0.998×0.01=0.00998; so 0.0019/0.01188≈0.16.
  6. 6 rolls; 36 rolls (a double six has probability 136).
  7. n22M =1062×232≈0.00012.

Harder

  1. Prove that if A and B are independent, so are A and "not B".
  2. Show that P(A∣B)=P(A) if and only if P(B∣A)=P(B) (for events with non-zero probability). Why is independence therefore symmetric?
  3. Explain why E[X+Y]=E[X]+E[Y] even when X and Y are dependent, using a table of joint probabilities.
  4. 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.
  5. How many random 64-bit ids can a system create before the chance of any collision reaches 1 in a million? (Use 1−e−x≈x for small x.)
Answers
  1. P(A and not B) =P(A)−P(A and B) =P(A)−P(A)P(B) =P(A)(1−P(B)) =P(A)P(not B).
  2. Both say P(A and B) =P(A)P(B): divide by P(B) for the first, by P(A) for the second. So independence is a property of the pair, not a direction.
  3. E[X+Y] =∑x,y(x+y)P(x,y) =∑x,yxP(x,y)+∑x,yyP(x,y). Summing P(x,y) over y gives P(x), so the first sum is ∑xxP(x)=E[X], and likewise the second is E[Y]. No independence was used.
  4. 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).
  5. Need n22×264≈10−6, so n≈2×1.8×1019×10−6≈6×106: about six million ids.

Challenge

  1. 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 23. 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 13. 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: 23. By Bayes: given the host opened door 3, P(prize at 1∣opens 3) =12·1312 =13 and P(prize at 2∣opens 3) =1·1312 =23. 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 13 to 23. 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 16. 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 P(A) and P(B). 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: 0≤P≤1; certain = 1; disjoint events add. Complement: 1−P(A). Overlap: P(A)+P(B)−P(A and B).
  • Equally likely: probability = favourable count ÷ total count.
  • Independent: P(A and B) =P(A)P(B), so surprises add.
  • Conditional: P(B∣A) =P(A and B)/P(A); product rule P(A and B) =P(A)P(B∣A).
  • Bayes: P(A∣B) =P(B∣A)P(A)/P(B); rare causes stay rare after weak evidence.
  • Expected value E[X]=∑kkP(X=k); always additive. Variance E[(X−E[X])2].
  • Law of large numbers: averages approach expectations; error shrinks like 1/n.
  • Binomial: (nk)pk(1−p)n−k, mean np. Geometric: wait 1/p on average.
  • Estimating: cx+1n+K (add-one); never zero.
  • Birthday: collisions likely after about M values; expected pairs n2/2M.

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: P(B∣A), the probability of B among the cases where A happened.
  • Bayes' theorem: P(A∣B) =P(B∣A)P(A)/P(B), 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 n 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 (c+1)/(n+K) so that no symbol gets probability zero; Laplace's rule of succession.
  • Birthday problem: the fact that among n random values from M, a repeat becomes likely once n is about M.