Probability and Statistics · Chapter 4

Chapter 4
Discrete random variables

Lectures 9–11 · counting what happens: distributions, expected values, and the named models that describe them

Cartoon: a scratch cardOne stick figure holds up a scratch card and says: I might win a thousand dollars! A second figure, holding a long receipt that trails to the ground, replies: You might. Now buy a thousand of them. $I might win$1,000!You might. Nowbuy a thousand.
a single outcome is unpredictable; the long-run average is not

How many passengers will show up for the flight? How many of the 20 bags tested will be fake? How many 911 calls will arrive in the next hour? How many guesses will it take to crack a password? Every one of these questions is about a count, and every one of them has an answer that is uncertain until it happens.

Chapter 3 gave us the language for uncertainty and, at the very end, the idea of a random variable: a rule that turns outcomes into numbers. This chapter puts that idea to work for counts. We will learn how to describe a count's whole distribution, how to boil it down to two numbers (its expected value and its spread), and then meet a small family of named distributions (binomial, geometric, negative binomial, hypergeometric and Poisson) that between them describe a remarkable number of real situations.

The named distributions are where probability starts to pay off. Instead of counting outcomes from scratch every time, you'll learn to recognize a situation ("this is a fixed number of independent yes/no trials, so it's binomial") and then use a formula, or one line of R, to answer any question about it. Recognizing the situation is the hard part, and it's a skill, so this chapter gives you a lot of practice at it.

Each named distribution is a small model of a mechanism, with one or two unknown numbers (its parameters) that control its behaviour: a success probability p, or a rate λ. The models serve both of our goals. For prediction, a model with known parameters tells us what to expect: how many passengers will show up, how likely a lab is to miss every fake. For inference, we turn this around: having seen the data, which model and which parameter values could have produced them? Was Paul the octopus guessing? Were the V-1 bombs aimed? Is a year with 12 great discoveries surprising, if the rate is about 3 a year? This chapter does the forward reasoning carefully, and points out the backward questions as they arise; Chapters 8 and 9 answer them properly.

Here is the route through the chapter.

Think About It: Before You Start

A raffle sells 1,000 tickets at $5 each, and there is a single prize of $2,000. Without calculating anything precise: is buying a ticket a good idea "on average"? Would your answer change if you were buying tickets to support a charity you care about? If you were the raffle's organizer? Keep your answers in mind: Section 4.2 makes "on average" precise, and you'll see that the number is only half the story.

On average, each ticket pays out $2,000 / 1,000 = $2, so a $5 ticket loses $3 on average: a bad bet in purely financial terms. But "on average" ignores what you care about. A supporter of the charity is happy to "lose" $3, because the money goes to a cause they value. The organizer collects $5,000 and pays $2,000, a guaranteed $3,000 for the charity: for them there's no uncertainty at all. The expected value is a tool for decisions, not the whole decision, and the same idea (costs and values, not just probabilities) runs back to the airline in Chapter 1.

Lecture 9 — Distributions, expected value and variance

4.1 Describing a discrete random variable

The probability mass function

A random variable is discrete if its possible values can be listed: x1,x2,x3,…, perhaps infinitely many, but with gaps between them. Counts are the main example. To describe a discrete random variable completely, we list its possible values and the probability of each one.

Definition: Probability Mass Function (PMF)

The probability mass function of a discrete random variable X is the function p(x)=Pr(X=x), defined for every real number x. It is positive only at the possible values of X (the support) and zero everywhere else. Every PMF satisfies

  1. p(x)≥0 for every x, and
  2. ∑xp(x)=1, the sum running over all possible values.

Both properties come straight from the axioms of Chapter 3: probabilities are never negative, and the events {X=x1},{X=x2},… are disjoint and between them cover the whole sample space, so their probabilities add to 1. The name "mass" suggests a helpful picture: think of one unit of mass (the total probability) shared out among the possible values, as weights on a number line.

A PMF can be given in three ways, and you should be comfortable moving between them: a table of values and probabilities, a formula for p(x), and a bar chart with a bar of height p(x) at each value x.

Example 4.1: Guessing a Pop Quiz, by Hand ★ lecture example

A surprise quiz has three true/false questions, and you haven't done the reading, so you guess each one by flipping a coin in your head. Let X be the number you get right. Find the PMF of X as a table, as a formula and as a picture, and check that it is a valid PMF.

List the outcomes. Write R for a right answer and W for a wrong one. There are 23=8 equally likely sequences (counting case 1 from Chapter 3), and X counts the R's:

outcome RRR RRW RWR WRR
X 3 2 2 2
outcome RWW WRW WWR WWW
X 1 1 1 0

Group the outcomes by the value of X. X=0 for one outcome, X=1 for three, X=2 for three, X=3 for one. Each outcome has probability 18, so

x 0 1 2 3
p(x) 18 38 38 18

As a formula. The number of sequences with exactly x right answers is the number of ways to choose which x of the 3 questions you got right, (3x) (counting case 3). So p(x)=(3x)(12)3,x=0,1,2,3. (Check: (31)/8=3/8.) This is our first binomial distribution; Section 4.4 generalizes it.

Valid? Every p(x)≥0, and 18+38+38+18=1. Yes.

As a picture, and a check in R (dbinom computes binomial probabilities, as we'll see in Section 4.4):

R
x <- 0:3
p <- dbinom(x, size = 3, prob = 0.5)
p
sum(p)
ggplot(data.frame(x, p), aes(x, p)) +
  geom_col(width = 0.4) +
  labs(x = "number of correct guesses, x", y = "p(x)")
output
[1] 0.125 0.375 0.375 0.125
[1] 1
Bar chart of the PMF of the number of correct guesses on a three-question true/false quizBar chart of the PMF of the number of correct guesses on a three-question true/false quiz: bars of height 1/8 at 0, 3/8 at 1, 3/8 at 2 and 1/8 at 3. The chart is symmetric about 1.5. 0.0 0.1 0.2 0.3 0 1 2 3 number of correct guesses, x p(x)

The bars for a PMF are drawn thin and separated, to show that X can only take these exact values. Notice the good news and the bad news: a pure guesser gets at least 2 out of 3 half the time, but all 3 only one time in 8. (A teacher who wants to tell guessers from students who know the material needs more than three questions: see Exercise 13.)

PMFs don't have to come from counting equally likely outcomes. Often they are estimated from data, using the empirical probabilities of Section 3.1.

Example 4.2: A Century of Great Discoveries ★ lecture example

R's discoveries dataset records the number of "great" inventions and scientific discoveries made in each year from 1860 to 1959, as listed in the World Almanac and Book of Facts (1975). Let X be the number of great discoveries in a year chosen at random from this century. Estimate the PMF of X, draw it, and estimate Pr(X≥4).

The empirical PMF is the table of relative frequencies (Section 3.1): for each value x, the fraction of the 100 years with exactly x discoveries.

R
d <- as.numeric(discoveries)       # 100 yearly counts, 1860 to 1959
table(d)
p_hat <- prop.table(table(d))       # relative frequencies
round(p_hat, 2)
output
d
 0  1  2  3  4  5  6  7  8  9 10 12 
 9 12 26 20 12  7  6  4  1  1  1  1 
d
   0    1    2    3    4    5    6    7    8    9   10   12 
0.09 0.12 0.26 0.20 0.12 0.07 0.06 0.04 0.01 0.01 0.01 0.01 
x 0 1 2 3 4 5 6 7 8 9 10 12
years 9 12 26 20 12 7 6 4 1 1 1 1

With exactly 100 years, each count divided by 100 is its estimated probability: p̂(2)=0.26, the most common value, and so on. The counts add to 100, so the estimates add to 1.

R
ggplot(data.frame(x = as.numeric(names(p_hat)), p = as.numeric(p_hat)), aes(x, p)) +
  geom_col(width = 0.4) +
  scale_x_continuous(breaks = 0:12) +
  labs(x = "great discoveries in a year, x", y = "estimated p(x)")
Bar chart of the estimated PMF of the number of great discoveries per year, 1860 to 1959Bar chart of the estimated PMF of the number of great discoveries per year, 1860 to 1959. The tallest bar is at 2 (0.26), then 3 (0.20), with 0.09 at 0, 0.12 at 1 and 0.12 at 4, then a long right tail of small bars out to 12. 0.0 0.1 0.2 0 1 2 3 4 5 6 7 8 9 10 11 12 great discoveries in a year, x estimated p(x)

The probability. {X≥4} is the disjoint union of {X=4},{X=5},…, so add the estimates: Pr̂(X≥4)=12+7+6+4+1+1+1+1100=33100=0.33. In R: mean(d >= 4).

A critical reading. What counts as "great" is someone's judgement, made decades later, and recent discoveries may not yet have been recognized: the measurement process (Section 1.4) shapes the data. Notice also p̂(11)=0: no year had exactly 11, though 12 happened once. An empirical PMF with zeros in the middle reminds us that it's an estimate of the true distribution, not the distribution itself.

The cumulative distribution function

Many questions ask about a range of values: "at most 2 visits", "more than 100 passengers", "between 3 and 6 calls". For these, it is convenient to have running totals of the PMF.

Definition: Cumulative Distribution Function (CDF)

The cumulative distribution function of a random variable X is F(x)=Pr(X≤x),for every real number x. For a discrete random variable, F(x)=∑t≤xp(t): add up the PMF over all values up to and including x.

Theorem: Properties of a CDF

For any random variable X with CDF F:

  1. 0≤F(x)≤1, and F never decreases: if a<b then F(a)≤F(b).
  2. F(x)→0 as x→−∞ and F(x)→1 as x→∞.
  3. For a<b, Pr(a<X≤b)=F(b)−F(a).
  4. Pr(X>x)=1−F(x).

For a discrete random variable, F is a step function: flat between possible values, and jumping up by p(x) at each possible value x.

  1. F(x) is a probability, so it lies in [0,1]. If a<b, then {X≤a}⊆{X≤b}, so F(a)≤F(b) by the subset rule of Section 3.3.
  2. Intuitively, {X≤x} shrinks to the empty set as x→−∞ and grows to the whole sample space as x→∞. (Making this rigorous needs a continuity property of probability that follows from axiom 3; we take it as given.)
  3. {X≤b} is the disjoint union of {X≤a} and {a<X≤b}, so F(b)=F(a)+Pr(a<X≤b). Rearrange.
  4. Complement rule: {X>x} is the complement of {X≤x}. ◼∎

Watch Out: Strict or Not Strict?

For a discrete random variable, < and ≤ are different: Pr(X≤2) includes Pr(X=2), and Pr(X<2)=Pr(X≤1) doesn't. Translate carefully: "at most 2" is X≤2; "fewer than 2" is X≤1; "at least 2" is X≥2, so Pr(X≥2)=1−F(1), not 1−F(2). This off-by-one mistake is the most common error in this chapter. (For the continuous random variables of Chapter 5, the distinction disappears.)

Example 4.3: Reading Probabilities from a CDF ★ lecture example

For the number of correct guesses X on the three-question quiz (Example 4.1), find the CDF, draw it, and use it to find Pr(X≤1), Pr(X<1), Pr(X≥2) and Pr(1<X≤3). If a passing grade needs at least 2 correct, what is the chance a guesser passes?

Running totals. Add the PMF from left to right:

x 0 1 2 3
p(x) 18 38 38 18
F(x) 18 48 78 88=1

Between the possible values, F stays flat. So in full, F(x)={0,x<0,18,0≤x<1,12,1≤x<2,78,2≤x<3,1,x≥3. Notice that F(1.5)=12, for example: "at most 1.5 right" means "at most 1 right".

R
ggplot(data.frame(x = c(-1, 0:3, 4)), aes(x)) +
  stat_function(fun = function(x) pbinom(x, 3, 0.5), geom = "step", n = 1001) +
  geom_point(data = data.frame(x = 0:3, F = pbinom(0:3, 3, 0.5)), aes(x, F)) +
  labs(x = "x", y = "F(x) = Pr(X ≤ x)")
Step plot of the CDF of the number of correct guesses on a three-question quizStep plot of the CDF of the number of correct guesses on a three-question quiz. The function is 0 to the left of 0, jumps to 1/8 at 0, to 1/2 at 1, to 7/8 at 2 and to 1 at 3, staying flat between jumps. Filled dots mark the value at each jump. 0.00 0.25 0.50 0.75 1.00 -1 0 1 2 3 4 x F(x) = Pr(X ≤ x)

The probabilities.

  • Pr(X≤1)=F(1)=12.
  • Pr(X<1)=Pr(X≤0)=F(0)=18.
  • Pr(X≥2)=1−Pr(X≤1)=1−F(1)=12. So a pure guesser passes half the time.
  • Pr(1<X≤3)=F(3)−F(1)=1−12=12. (Check: that's Pr(X=2)+Pr(X=3)=38+18.)

In R, pbinom(1, 3, 0.5) gives F(1). Every named distribution has a "p" function for its CDF.

The widget below lets you shape a PMF yourself and watch its CDF respond. The triangle under the PMF is the expected value, the subject of the next section.

PMF, CDF and the balance point

Design your own PMF on the values 1 to 5: the sliders set a weight for each value. The weights are rescaled so that they always add up to 1. The left panel is the PMF, with the expected value drawn as the point where the bars would balance on a seesaw. The right panel is the CDF, a staircase that jumps by Pr(X = x) at each value.

Bar chart of the probability mass function with a fulcrum at the expected valueBar chart of the probability mass function with a fulcrum at the expected value. Step plot of the cumulative distribution functionStep plot of the cumulative distribution function.

Check Yourself

Which of these could be a PMF on the values 1, 2, 3?

A random variable has CDF values F(1)=0.2, F(2)=0.7, F(3)=0.9, F(4)=1, and takes only the values 1, 2, 3, 4. Find Pr(X≥3).

Using the same CDF, find Pr(X=2).

Think About It: A Model or the Data?

In Example 4.1 the PMF came from a model (each guess is right with probability ½). In Example 4.2 it came from data (100 years of discoveries). Give one advantage of each approach. If you wanted to predict the number of great discoveries in 2030, which would you trust, and why might neither be very good?

A model gives exact probabilities for every value, including ones never seen in the data (such as 11 discoveries), and it explains why the probabilities are what they are. Data need no assumptions: they show what actually happened, warts and all. For 2030, neither is ideal: the data describe 1860–1959, and the rate of discovery (and what counts as "great") has surely changed since; a model fitted to old data inherits the same problem. Good prediction needs both a sensible model and data from a process that still works the same way.

Key Takeaways

  • A discrete random variable is described by its PMF p(x)=Pr(X=x): non-negative values adding to 1. Show it as a table, a formula or a bar chart.
  • The CDF F(x)=Pr(X≤x) is a running total; for discrete X it's a step function jumping by p(x) at each value.
  • Pr(a<X≤b)=F(b)−F(a) and Pr(X>x)=1−F(x). Watch the difference between < and ≤.
  • A PMF can be computed from a model, or estimated from data as relative frequencies.

4.2 Expected value: the long-run average

One number for the centre

In Chapter 2, the mean of a dataset summarized its centre. A random variable has a centre too, and it is defined in exactly the same spirit.

Suppose a die is rolled 600 times. We'd expect about 100 of each face, so the average of the 600 rolls should be about 100×1+100×2+⋯+100×6600=1×16+2×16+⋯+6×16=3.5. The average of many plays is each value, times the fraction of the time it occurs, added up. In the long run those fractions are the probabilities. That gives the definition.

Definition: Expected Value

The expected value (or mean, or expectation) of a discrete random variable X with PMF p(x) is E[X]=∑xxp(x), the sum of each possible value times its probability. (If X takes infinitely many values, we require the sum ∑x|x|p(x) to be finite; otherwise E[X] doesn't exist.) It is often written μ or μX.

There are two ways to picture the expected value, and both are worth keeping.

Notice that E[X] need not be a possible value of X: a die never shows 3.5. "Expected" is a historical name, not a prediction of any single outcome.

The expected value is the long-run average

Choose a random quantity and play it over and over. The left panel compares the PMF (bars) with how often each value has actually come up so far (dots). The right panel tracks the running average of everything played so far; the dashed line is the expected value E[X]. Early on the average wanders; in the long run it settles on E[X], even though a single play may never equal E[X].

Bar chart of the PMF with dots showing observed relative frequenciesBar chart of the PMF with dots showing observed relative frequencies. Running average of the plays so far, with the expected value as a dashed lineRunning average of the plays so far, with the expected value as a dashed line.

Example 4.4: How Many Discoveries in a Typical Year? ★ lecture example

Using the empirical PMF of great discoveries per year from Example 4.2, find E[X] by hand and in R. Compare it with the average of the 100 yearly counts. What does the number mean?

By hand. Multiply each value by its estimated probability and add: E[X]=0(0.09)+1(0.12)+2(0.26)+3(0.20)+4(0.12)+5(0.07)+6(0.06)+7(0.04)+8(0.01)+9(0.01)+10(0.01)+12(0.01)=0+0.12+0.52+0.60+0.48+0.35+0.36+0.28+0.08+0.09+0.10+0.12=3.10.E[X]=0(0.09)+1(0.12)+2(0.26)+3(0.20)+4(0.12)+5(0.07)+6(0.06)+7(0.04)+8(0.01)+9(0.01)+10(0.01)+12(0.01)=0+0.12+0.52+0.60+0.48+0.35+0.36+0.28+0.08+0.09+0.10+0.12=3.10.

In R, the same calculation is sum(x * p). Compare it with the ordinary average of the data:

R
x <- as.numeric(names(p_hat))
sum(x * p_hat)          # expected value of the empirical PMF
mean(d)                 # the average of the 100 yearly counts
output
[1] 3.1
[1] 3.1

Both give 3.1. That's no coincidence: averaging 100 numbers is the same as weighting each distinct value by the fraction of the time it occurs, which is exactly what ∑xp̂(x) does. The expected value of an empirical distribution is the sample mean of Chapter 2. For a model distribution, E[X] is the mean we'd see in the long run.

Meaning. Averaged over the century, about 3.1 great discoveries were made per year: 310 in 100 years. No year had 3.1 discoveries, but a historian estimating how many great discoveries to expect in a decade would say about 31. Try the "great discoveries" option in the widget above: the running average of simulated years settles at 3.1.

Prediction and inference. As a prediction, 3.1 is our best guess (under squared loss) for the number of great discoveries in a year like these. As an inference, it estimates the underlying rate of discovery in that century. Notice that the two uses need different caveats: the prediction assumes future years behave like 1860–1959; the inference assumes the years are a fair record of what happened.

Example 4.5: Is a Powerball Ticket Worth $2? ★ lecture example

A Powerball ticket costs $2. Its prizes and odds, from the official prize chart, are:

match prize odds (1 in ...)
Powerball only $4 38.32
1 + Powerball $4 91.98
2 + Powerball $7 701.33
3 numbers $7 579.76
3 + Powerball $100 14,494.11
4 numbers $100 36,525.17
4 + Powerball $50,000 913,129.18
5 numbers $1,000,000 11,688,053.52
5 + Powerball jackpot J 292,201,338

(a) Ignoring the jackpot, what is the expected prize per ticket? (b) How big must the jackpot be for a ticket to be worth $2 "on average"? (c) Why is even that answer too optimistic?

Set up. Let W be the prize on one ticket. Each tier's probability is 1 divided by its odds, and the tiers are disjoint (a ticket wins at most one), so by the definition of expected value E[W]=∑tiers(prize)×Pr(tier).

(a) The non-jackpot tiers contribute, for example, 4/38.32≈$0.104 for the first and 1,000,000/11,688,053.52≈$0.086 for the $1 million tier. Adding all eight in R:

R
prize <- c(4, 4, 7, 7, 100, 100, 50000, 1e6)
odds  <- c(38.32, 91.98, 701.33, 579.76, 14494.11, 36525.17, 913129.18, 11688053.52)
round(prize / odds, 4)         # each tier's contribution, in dollars
sum(prize / odds)              # expected non-jackpot prize per ticket
(2 - sum(prize / odds)) * 292201338    # break-even jackpot
output
[1] 0.1044 0.0435 0.0100 0.0121 0.0069 0.0027 0.0548 0.0856
[1] 0.3198782
[1] 490933824

So the non-jackpot prizes are worth about 32 cents per $2 ticket. Interestingly, the $50,000 and $1 million tiers contribute 14 cents of that between them: the rare big prizes matter about as much as the frequent small ones.

(b) The jackpot adds J/292,201,338. For E[W]=2 we need 0.32+J292,201,338=2⇒J≈1.68×292,201,338≈$491 million.

(c) Three reasons a $491 million advertised jackpot still isn't a fair bet. The advertised jackpot is paid over 29 years; the lump-sum cash value is roughly half. Large prizes are taxed heavily. And when the jackpot is huge, ticket sales soar, so the chance of having to share the jackpot with other winners rises. Each of these cuts the expected value well below $2. On expected value alone, a Powerball ticket is a poor investment; people buy them for the dream, which is a perfectly reasonable thing to pay $2 for, as long as you know that's what you're buying.

Source: Powerball prize chart, powerball.com.

Where the expected value comes from. A bar chart of each tier's contribution (prize × probability) shows that the rare large prizes contribute as much as the common small ones:

R
tiers <- c("PB only", "1+PB", "2+PB", "3", "3+PB", "4", "4+PB", "5")
d <- data.frame(tier = factor(tiers, levels = tiers), cents = 100 * prize / odds)
ggplot(d, aes(tier, cents)) + geom_col(width = 0.6) +
  labs(x = "prize tier (numbers matched)", y = "cents per ticket")
Bar chart of the contribution of each Powerball non-jackpot prize tier to the expected…Bar chart of the contribution of each Powerball non-jackpot prize tier to the expected value of a ticket, in cents. The Powerball-only tier contributes about 10 cents, 1 + Powerball about 4, the next three tiers about 1 cent each, 4 numbers about a quarter of a cent, 4 + Powerball (50,000 dollars) about 5.5 and 5 numbers (1 million dollars) about 8.5. 0.0 2.5 5.0 7.5 10.0 PB only 1+PB 2+PB 3 3+PB 4 4+PB 5 prize tier (numbers matched) cents per ticket

Expected values of functions

Often we need the expected value not of X itself, but of something computed from it: the cost c(X) of a decision, or X2 (which we'll need for the variance). There's no need to find the distribution of the new quantity first.

Theorem: Expected Value of a Function of X

For any function g, E[g(X)]=∑xg(x)p(x), provided the sum of |g(x)|p(x) is finite.

Y=g(X) takes the value y exactly when X takes one of the values x with g(x)=y. So Pr(Y=y)=∑x:g(x)=yp(x), and E[Y]=∑yyPr(Y=y)=∑y∑x:g(x)=yg(x)p(x)=∑xg(x)p(x). The last step just regroups the terms: every x appears exactly once, in the group for y=g(x). ◼∎

In words: to find the average of g(X), apply g to each possible value and weight by the same probabilities. (Some books call this the "law of the unconscious statistician", because it's what people do without thinking.)

Example 4.6: The Overbooking Bill, Exactly ★ lecture example

In Chapter 1, an airline sold 110 tickets for a 100-seat plane; each ticket holder shows up with probability 0.9, independently. An empty seat costs $250 and a bumped passenger $1000. The simulation in Example 1.1 estimated the average cost per flight at about $1240. Compute it exactly.

Set up. Let X be the number who show up; its PMF is binomial (Section 4.4), and R's dbinom(x, 110, 0.9) gives Pr(X=x). The cost is a function of X: c(x)={250(100−x),x<100,1000(x−100),x≥100.

Apply the theorem. E[c(X)]=∑x=0110c(x)Pr(X=x), a sum of 111 terms that R does in one line:

R
x <- 0:110
p <- dbinom(x, size = 110, prob = 0.9)
cost <- ifelse(x < 100, 250 * (100 - x), 1000 * (x - 100))
sum(cost * p)                       # expected cost per flight
# repeat for every number of tickets from 95 to 120
exp_cost <- sapply(95:120, function(n) {
  x <- 0:n
  sum(ifelse(x < 100, 250 * (100 - x), 1000 * (x - 100)) * dbinom(x, n, 0.9))
})
(95:120)[which.min(exp_cost)]       # the best number of tickets
output
[1] 1240.143
[1] 108

The exact expected cost is $1240.14, matching the simulation's estimate. Doing the same for every number of tickets shows that 108 tickets minimizes the expected cost (about $1041 per flight), as the widget in Chapter 1 showed.

R
ggplot(data.frame(n = 95:120, exp_cost), aes(n, exp_cost)) +
  geom_line() + geom_point(size = 1) +
  geom_point(data = data.frame(n = 108, exp_cost = min(exp_cost)), size = 3.5, colour = "orange") +
  labs(x = "tickets sold", y = "expected cost ($)")
Line plot of the expected cost per flight against the number of tickets sold, from 95 to…Line plot of the expected cost per flight against the number of tickets sold, from 95 to 120. The curve falls from about 3,600 dollars at 95 tickets to a minimum of about 1,040 dollars at 108 tickets, marked with a point, then rises steeply to over 8,000 dollars at 120. 2000 4000 6000 8000 95 100 105 110 115 120 tickets sold expected cost ($)

Chapter 1's question ("how many tickets?") is now a precise calculation: choose the decision that minimizes the expected value of the loss.

Theorem: Linearity of Expectation

For any random variables X and Y and constants a and b:

  1. E[aX+b]=aE[X]+b;
  2. E[X+Y]=E[X]+E[Y], whether or not X and Y are independent.

Part 1. Use the theorem above with g(x)=ax+b, then split the sum and use ∑xp(x)=1: E[aX+b]=∑x(ax+b)p(x)=a∑xxp(x)+b∑xp(x)=aE[X]+b. Part 2 needs the joint distribution of X and Y, which is the subject of Chapter 6; we prove it there and use it now. ◼∎

Linearity is the most useful property in the whole chapter, and part 2 is surprisingly powerful because it needs no independence. The expected total of many random quantities is the total of their expected values, whatever the connections between them.

Example 4.7: A Secret Santa Disaster

Twenty friends organize a Secret Santa: each writes their name on a slip, the slips are shuffled in a hat, and each person draws one, to buy a present for whoever is named. Anyone who draws their own name spoils the game. How many people do you expect to draw their own name?

Finding the full distribution of the number of "self-draws" is hard. The expected value is easy with indicators (Section 3.8). Let Ik=1 if friend k draws their own name and 0 otherwise. The total number of self-draws is M=I1+I2+⋯+I20.

Each friend is equally likely to draw any of the 20 slips, so Pr(Ik=1)=120, and E[Ik]=1×120+0×1920=120. By linearity, E[M]=E[I1]+⋯+E[I20]=20×120=1. On average, exactly one person draws their own name, and the answer would be 1 with 10 friends or 1,000. The indicators are not independent (if 19 friends have their own names, so does the 20th), but linearity doesn't care. A simulation agrees, and also shows how often the game survives with no self-draws at all:

R
set.seed(20)
self_draws <- replicate(10000, sum(sample(20) == 1:20))
mean(self_draws)          # close to 1
mean(self_draws == 0)     # fraction of games with nobody drawing themselves
output
[1] 0.9844
[1] 0.3721

About 37% of shuffles work first time, so expect to reshuffle more often than not. (The exact answer is very close to 1/e≈0.368, for any reasonably large group: a famous result called the matching problem.)

The whole distribution. A bar chart of the 10,000 simulated games shows how many people typically draw their own name. The orange dots are the probabilities from a Poisson distribution with mean 1 (Section 4.7), which turns out to be an excellent approximation:

R
d <- as.data.frame(table(factor(self_draws, levels = 0:6)) / 10000)
names(d) <- c("k", "prop")
d$k <- as.numeric(as.character(d$k))
ggplot(d, aes(k, prop)) + geom_col(width = 0.5) +
  geom_point(aes(y = dpois(k, 1)), colour = "orange", size = 3) +
  labs(x = "number of people who draw their own name", y = "proportion of games")
Bar chart of the number of people who draw their own name in 10,000 simulated Secret…Bar chart of the number of people who draw their own name in 10,000 simulated Secret Santa draws with 20 people. About 37% have 0, 37% have 1, 18% have 2, 6% have 3 and very few have 4 or more. Orange dots for a Poisson distribution with mean 1 sit almost exactly on the bars. 0.0 0.1 0.2 0.3 0 2 4 6 number of people who draw their own name proportion of games

Check Yourself

X takes the values 0, 1, 2, 3 with probabilities 0.1, 0.2, 0.2, 0.5. Find E[X].

In the raffle at the start of the chapter (1,000 tickets at $5, one $2,000 prize), what is the expected net gain from one ticket, in dollars?

If E[X]=5, what is E[3X+2]?

Think About It: When the Average Is the Wrong Target

A hospital uses the expected number of emergency admissions per night, 12, to decide how many beds to keep free. Why is planning for exactly the expected value a bad idea? What would a better rule look like?

On about half of nights (roughly, since the distribution is not symmetric), admissions exceed the average, and patients would have nowhere to go. The cost of a shortage (a patient turned away) is far bigger than the cost of an empty bed, so the loss is lopsided, and the best plan is a high quantile of the distribution (Chapter 2's loss-function interlude), for example enough beds to cover 95% or 99% of nights. The expected value is the right target only when over- and under-shooting cost the same. To choose the quantile you need the whole distribution, not just its mean: that is what the named models in this chapter provide.

Key Takeaways

  • E[X]=∑xxp(x): the long-run average, and the balance point of the PMF. It need not be a possible value.
  • E[g(X)]=∑xg(x)p(x): no need to find the distribution of g(X) first.
  • Linearity: E[aX+b]=aE[X]+b and E[X+Y]=E[X]+E[Y], even without independence.
  • The best decision under uncertainty often minimizes an expected loss, but expected value isn't the whole story when a bad outcome would be unbearable.

4.3 Variance: how far from the average?

Two jobs both pay $50,000 a year on average. One pays exactly $50,000; the other pays $20,000 or $80,000 with equal chance. Most people would not call them equivalent. As in Chapter 2, a centre needs a spread to go with it.

Definition: Variance and Standard Deviation of a Random Variable

The variance of a random variable X with mean μ=E[X] is the expected squared distance from the mean: Var[X]=E[(X−μ)2]=∑x(x−μ)2p(x). The standard deviation is SD[X]=Var[X], often written σ; the variance is then σ2.

Compare with the sample variance of Chapter 2: there we averaged the squared deviations of the data (dividing by n−1); here we average the squared deviations of the possible values, weighted by their probabilities. The standard deviation is in the same units as X and measures a typical distance from the mean.

Squaring and summing is tedious by hand. This shortcut is usually quicker.

Theorem: Shortcut Formula for the Variance

Var[X]=E[X2]−(E[X])2. In words: the mean of the square, minus the square of the mean.

Expand the square and use linearity, remembering that μ is a constant: Var[X]=E[X2−2μX+μ2]=E[X2]−2μE[X]+μ2=E[X2]−2μ2+μ2=E[X2]−μ2.◼Var[X]=E[X2−2μX+μ2]=E[X2]−2μE[X]+μ2=E[X2]−2μ2+μ2=E[X2]−μ2.◼∎

Since a variance can't be negative, the theorem also shows that E[X2]≥(E[X])2 always: the mean of the squares is at least the square of the mean.

Example 4.8: Deal or No Deal? ★ lecture example

On a game show you are offered three choices.

  • A: take $50,000 now.
  • B: flip a coin: $100,000 for heads, nothing for tails.
  • C: draw a card from four: one card pays $200,000, the other three nothing.

Find the expected value and the standard deviation of the prize for each choice, by hand. Which would you choose, and why?

Expected values. E[A]=50,000,E[B]=100,000×12+0×12=50,000,E[C]=200,000×14+0×34=50,000.E[A]=50,000,E[B]=100,000×12+0×12=50,000,E[C]=200,000×14+0×34=50,000. All three have the same expected value. On average, over many plays, they would pay the same.

Variances, by the shortcut formula Var=E[X2]−(E[X])2. Work in thousands of dollars to keep the numbers small:

  • A always pays 50, so E[A2]=502=2500 and Var[A]=2500−2500=0: no risk at all.
  • B: E[B2]=1002×12=5000, so Var[B]=5000−2500=2500 and SD[B]=50.
  • C: E[C2]=2002×14=10,000, so Var[C]=10,000−2500=7500 and SD[C]≈86.6.

So the standard deviations are $0, $50,000 and about $86,600: the same average, increasingly risky.

R
sd_of <- function(x, p) { mu <- sum(x * p); sqrt(sum(x^2 * p) - mu^2) }
c(A = sd_of(50000, 1),
  B = sd_of(c(0, 100000), c(1/2, 1/2)),
  C = sd_of(c(0, 200000), c(3/4, 1/4)))
output
       A        B        C 
    0.00 50000.00 86602.54 

Which to choose? Expected value can't decide this: they're tied. Most people take A, because $50,000 for certain changes their life and a 75% chance of nothing (choice C) is painful. A billionaire, for whom $50,000 is small change, might reasonably take C for the fun of it. The standard deviation measures the risk; how much risk you should take depends on your circumstances, which is the loss function idea of Chapter 2 again. The real game show Deal or No Deal offered contestants exactly this kind of choice, and economists studied the contestants' decisions to learn how people value risk.

The three choices side by side. Same balance point, very different spread:

R
choices <- data.frame(
  choice = rep(c("A", "B", "C"), c(1, 2, 2)),
  prize = c(50, 0, 100, 0, 200), prob = c(1, 0.5, 0.5, 0.75, 0.25))
ggplot(choices, aes(prize, prob)) + geom_col(width = 12) +
  geom_vline(xintercept = 50, linetype = "dashed") +
  facet_wrap(~ choice) + scale_x_continuous(breaks = c(0, 100, 200)) +
  theme(panel.spacing = unit(1.2, "lines")) +
  labs(x = "prize (thousands of dollars)", y = "probability")
Three bar charts of the prize distributions for the three game-show choicesThree bar charts of the prize distributions for the three game-show choices. Choice A has a single bar of probability 1 at 50 thousand dollars. Choice B has bars of 0.5 at 0 and 100 thousand. Choice C has a bar of 0.75 at 0 and 0.25 at 200 thousand. A dashed line at 50 thousand marks the common expected value. A B C 0 100 200 0 100 200 0 100 200 0.00 0.25 0.50 0.75 1.00 prize (thousands of dollars) probability

Theorem: Variance of a Linear Function

For constants a and b, Var[aX+b]=a2Var[X],SD[aX+b]=|a|SD[X].

By linearity, E[aX+b]=aμ+b, so (aX+b)−(aμ+b)=a(X−μ). Then Var[aX+b]=E[a2(X−μ)2]=a2E[(X−μ)2]=a2Var[X]. Take square roots for the SD. ◼∎

This matches the "changing units" theorem for data in Chapter 2: adding a constant shifts the centre but not the spread. For instance, if every game-show prize in Example 4.8 were taxed at a flat 30%, the take-home prize 0.7X would have standard deviation 0.7SD[X]; if instead a $1,000 appearance fee were added to every prize, the standard deviation wouldn't change at all.

Watch Out: Variances Don't Always Add

Expected values always add: E[X+Y]=E[X]+E[Y]. Variances add only for independent random variables: Var[X+Y]=Var[X]+Var[Y] if X and Y are independent (proved in Chapter 6). If they move together, the variance of the sum is bigger; if they move in opposite directions, smaller. And Var[X−Y] is Var[X]+Var[Y] for independent variables, not the difference: subtracting a random quantity adds uncertainty.

Think About It: What Does a Standard Deviation of Risk Mean?

Two investments each return $100 on average. Investment A has a standard deviation of $5; investment B, $60. Which would you choose for money you need next month for rent? For money you won't touch for 30 years? Why might the answer differ?

For rent money, A: you need to be nearly sure of having it, and B could easily return much less than $100. For long-term money, many people accept B's ups and downs if, as is common in practice, riskier investments also have higher average returns; over 30 years, the good and bad years partly average out. Spread measures risk, and whether risk matters depends on what the money is for: again, the decision depends on the loss function, not just the distribution.

Check Yourself

X takes the values 0, 1, 2, 3 with probabilities 0.1, 0.2, 0.2, 0.5, so E[X]=2.1. Find Var[X].

If Var[X]=4, what is Var[4−3X]?

Key Takeaways

  • Var[X]=E[(X−μ)2]=E[X2]−μ2; SD[X]=Var[X], in the units of X.
  • Var[aX+b]=a2Var[X]: shifting doesn't change spread.
  • Variances add for independent random variables only.

Lecture 10 — Binomial, geometric and hypergeometric models

4.4 Bernoulli and binomial: counting successes

One trial

The simplest random variable of all records whether something happened: a test is positive or not, a passenger shows up or not, a coin lands heads or not. Statisticians call the two outcomes "success" (coded 1) and "failure" (coded 0), whatever they actually are; a "success" can be a disease, a crime or a defect.

Definition: Bernoulli Distribution

A random variable X has the Bernoulli distribution with success probability p, written X∼Bern(p), if Pr(X=1)=p,Pr(X=0)=1−p. A single experiment with two outcomes is called a Bernoulli trial.

Theorem: Mean and Variance of a Bernoulli Random Variable

If X∼Bern(p), then E[X]=p and Var[X]=p(1−p).

E[X]=1⋅p+0⋅(1−p)=p. Since X is 0 or 1, X2=X, so E[X2]=p too, and by the shortcut formula Var[X]=p−p2=p(1−p). ◼∎

The variance p(1−p) is largest when p=12 (the hardest outcome to predict) and zero when p=0 or 1 (no uncertainty at all).

Explore the Bernoulli distribution

Move the sliders to change the parameters and watch the shape change. The red triangle marks the expected value and the red bar spans one standard deviation either side. Move x to highlight Pr(X ≤ x); the R command that computes it is shown below. Press draw a sample to simulate 200 values: the orange lines show how often each value came up, and they sit close to the bars.

Bar chart of the probability mass function for the chosen parameters, with the expected…Bar chart of the probability mass function for the chosen parameters, with the expected value and one standard deviation marked, and the bars up to x highlighted.

Many trials: the binomial distribution

Now repeat a Bernoulli trial n times and count the successes. If a drug test gives a false positive for 5% of clean athletes, how many false positives should we expect among 20 clean athletes? What's the chance of none at all? Example 4.1 (guessing a true/false quiz) already did this for n=3 and p=12. Here is the general story.

Theorem: The Binomial Distribution

Suppose we perform n trials such that

  1. each trial has two outcomes, success or failure;
  2. the trials are independent;
  3. each trial has the same success probability p.

Let X be the number of successes. Then X has the binomial distribution, X∼Bin(n,p), with PMF Pr(X=x)=(nx)px(1−p)n−x,x=0,1,…,n.

One particular sequence. Consider any one sequence of n outcomes with exactly x successes, such as S S F S F… The trials are independent, so its probability is the product of the probabilities of its outcomes: x factors of p and n−x factors of 1−p, giving px(1−p)n−x whatever the order.

How many such sequences? A sequence with x successes is determined by choosing which x of the n trials are the successes: (nx) ways (counting case 3).

Add them up. The sequences are disjoint outcomes, each with the same probability, so Pr(X=x)=(nx)×px(1−p)n−x. These probabilities add to 1 by the binomial theorem: ∑x(nx)px(1−p)n−x=(p+(1−p))n=1. ◼∎

Each piece of the formula has a job: px(1−p)n−x is the probability of one arrangement, and (nx) counts the arrangements. A Galton board makes this visible: each ball makes n left-or-right "trials", and the number of rights it takes decides where it lands.

A binomial machine (Galton board)

Each ball falls through n rows of pegs. At every peg it goes right (a success) with probability p and left otherwise, independently. The bin it lands in is its number of successes, so each ball is one draw from Bin(n, p). Drop balls and compare the pile (orange) with the binomial probabilities (blue dots), scaled to the number of balls.

A triangular board of pegs above a row of binsA triangular board of pegs above a row of bins. Balls drop through the pegs and pile up in the bins, next to dots showing the expected binomial counts.

Theorem: Mean and Variance of a Binomial Random Variable

If X∼Bin(n,p), then E[X]=np,Var[X]=np(1−p).

Write X=I1+I2+⋯+In, where Ik=1 if trial k is a success and 0 otherwise. Each Ik∼Bern(p), with mean p and variance p(1−p).

  • By linearity, E[X]=p+p+⋯+p=np.
  • The trials are independent, so the variances add (Chapter 6 proves this): Var[X]=np(1−p). ◼∎

The mean np is common sense: 20 athletes, each with a 5% chance, gives 1 false positive on average. Proving it from the PMF directly would take a page of algebra; the indicator trick takes one line.

Idea: Algorithm: Is It Binomial?

Before using the binomial formula, check the four conditions. A memory aid is BINS:

  • Binary: each trial has two outcomes (success or failure)?
  • Independent: does one trial's outcome leave the others' probabilities unchanged?
  • N: is the number of trials n fixed in advance?
  • Same p: does every trial have the same success probability?

Then name n, p and what counts as a "success", and write X∼Bin(n,p) before calculating anything.

In R, every named distribution has four functions, named by a letter plus the distribution's short name:

function gives binomial example
d... the PMF, Pr(X=x) dbinom(x, n, p)
p... the CDF, Pr(X≤x) pbinom(x, n, p)
q... a quantile: the smallest x with F(x)≥ a given probability qbinom(0.95, n, p)
r... random draws (simulation) rbinom(10, n, p)

Example 4.9: Paul the Octopus ★ lecture example

During the 2010 football World Cup, an octopus called Paul, living in an aquarium in Oberhausen, Germany, was offered two boxes of food before each of Germany's matches, each box marked with a team's flag. The box he opened first was taken as his prediction. Paul correctly "predicted" all 7 of Germany's matches and then the final (Spain beat the Netherlands): 8 out of 8. Including the European Championship two years earlier, his record was 12 correct out of 14.

(a) If Paul was simply choosing at random, what is the probability of 8 out of 8? (b) Of 12 or more out of 14? (c) Hundreds of animals around the world (other octopuses, parakeets, elephants, guinea pigs) were "predicting" World Cup matches. If 200 animals each guessed 8 matches at random, how many would you expect to get all 8 right?

Is it binomial? Each prediction is right or wrong (binary); a random chooser's guesses are independent; the number of matches is fixed; and each guess is right with probability 12 (same p). So the number right is binomial.

(a) X∼Bin(8,12): Pr(X=8)=(12)8=1256≈0.0039.

(b) Y∼Bin(14,12). "12 or more" is Y=12,13 or 14: Pr(Y≥12)=(1412)+(1413)+(1414)214=91+14+116,384=10616,384≈0.0065.

R
dbinom(8, 8, 0.5)                    # (a)
1 - pbinom(11, 14, 0.5)              # (b) Pr(Y >= 12)
200 * dbinom(8, 8, 0.5)              # (c) expected number of perfect animals
output
[1] 0.00390625
[1] 0.006469727
[1] 0.78125

(c) Each animal is perfect with probability 1256, so by linearity (with indicators, as in Example 4.7) the expected number of perfect animals is 200×1256≈0.78. With a few hundred animals predicting, it's quite likely that some animal gets them all right by luck alone, and that animal is the one that becomes famous.

The lesson is the birthday problem again (Example 3.9): a one-in-256 event is rare for one animal and unremarkable among hundreds. We only heard about Paul because he got them right; nobody reported on the parakeet that got 4 out of 8. Selecting the winners after the fact is how many "amazing" track records, from stock-pickers to psychics, are made. Chapter 9 calls this the problem of multiple testing.

How surprising is 8 out of 8? The PMF of Bin(8,12) shows how far Paul's result sits from what guessing usually produces:

R
d <- data.frame(x = 0:8, p = dbinom(0:8, 8, 0.5), paul = 0:8 == 8)
ggplot(d, aes(x, p, fill = paul)) + geom_col(width = 0.5) +
  scale_fill_manual(values = c("grey60", "orange"), guide = "none") +
  scale_x_continuous(breaks = 0:8) +
  labs(x = "correct predictions out of 8, if guessing", y = "probability")
Bar chart of the binomial distribution with 8 trials and success probability one halfBar chart of the binomial distribution with 8 trials and success probability one half: a symmetric hump peaking at 4 correct (about 0.27) and falling to about 0.004 at 0 and at 8. The bar at 8, Paul's result, is highlighted in orange. 0.0 0.1 0.2 0 1 2 3 4 5 6 7 8 correct predictions out of 8, if guessing probability

This is inference. We asked: how probable is the observed result if the mechanism is pure guessing? Very improbable for one animal, but not for the luckiest of hundreds. Chapter 9 formalizes this as a hypothesis test and its p-value.

Example 4.10: False Positives in a Clean Team ★ lecture example

A drug test gives a false positive for 5% of athletes who don't use the drug, independently from athlete to athlete. A team of 20 clean athletes is tested. Find (a) the probability of no positives, (b) exactly one positive, (c) at least one positive, and (d) the mean and standard deviation of the number of positives. Do (a) to (c) by hand, then in R.

Is it binomial? Binary (positive or not); independent (stated); n=20 fixed; same p=0.05 for every clean athlete. So X = number of false positives ∼Bin(20,0.05), with "success" meaning a positive test. (A "success" is just the outcome we count, here an unwelcome one.)

(a) Pr(X=0)=(200)(0.05)0(0.95)20=0.9520≈0.358.

(b) Pr(X=1)=(201)(0.05)1(0.95)19=20×0.05×0.9519≈0.377.

(c) "At least one" is easiest through the complement: Pr(X≥1)=1−Pr(X=0)≈1−0.358=0.642.

(d) E[X]=np=20×0.05=1 and SD[X]=np(1−p)=20×0.05×0.95=0.95≈0.97.

R
dbinom(0, size = 20, prob = 0.05)       # (a)
dbinom(1, size = 20, prob = 0.05)       # (b)
1 - pbinom(0, size = 20, prob = 0.05)   # (c): 1 - Pr(X <= 0)
round(dbinom(0:5, 20, 0.05), 4)         # the first few PMF values
output
[1] 0.3584859
[1] 0.3773536
[1] 0.6415141
[1] 0.3585 0.3774 0.1887 0.0596 0.0133 0.0022
R
ggplot(data.frame(x = 0:6, p = dbinom(0:6, 20, 0.05)), aes(x, p)) +
  geom_col(width = 0.4) +
  labs(x = "false positives among 20 clean athletes", y = "probability")
Bar chart of the binomial distribution with n equal to 20 and p equal to 0.05, for 0 to 6…Bar chart of the binomial distribution with n equal to 20 and p equal to 0.05, for 0 to 6 positives. The tallest bars are at 0 and 1 (about 0.36 and 0.38), then 0.19 at 2, 0.06 at 3, and almost nothing beyond 4. 0.0 0.1 0.2 0.3 0 2 4 6 false positives among 20 clean athletes probability

What it means. Even with no drug users at all, there's nearly a two-in-three chance that someone tests positive. A single positive on a large team is not, by itself, evidence of drug use; that's why positive screens are confirmed with a second, more specific test (and why Section 3.6's Bayes calculation matters).

Explore the binomial distribution

Move the sliders to change the parameters and watch the shape change. The red triangle marks the expected value and the red bar spans one standard deviation either side. Move x to highlight Pr(X ≤ x); the R command that computes it is shown below. Press draw a sample to simulate 200 values: the orange lines show how often each value came up, and they sit close to the bars.

Bar chart of the probability mass function for the chosen parameters, with the expected…Bar chart of the probability mass function for the chosen parameters, with the expected value and one standard deviation marked, and the bars up to x highlighted.

Example 4.11: The Chance Someone Is Bumped

Return to the airline: 110 tickets, each ticket holder showing up with probability 0.9 independently. What is the probability that more than 100 show up? How many tickets could the airline sell and keep that probability below 5%?

X∼Bin(110,0.9), and we want Pr(X>100)=1−Pr(X≤100):

R
1 - pbinom(100, size = 110, prob = 0.9)
# the same for every number of tickets from 100 to 115
n <- 100:115
data.frame(tickets = n, p_bump = round(1 - pbinom(100, n, 0.9), 3))
output
[1] 0.3289856
   tickets p_bump
1      100  0.000
2      101  0.000
3      102  0.000
4      103  0.001
5      104  0.006
6      105  0.017
7      106  0.040
8      107  0.081
9      108  0.143
10     109  0.227
11     110  0.329
12     111  0.441
13     112  0.554
14     113  0.660
15     114  0.752
16     115  0.826

The probability is 0.329, matching the simulation in Example 1.1. Scanning the table, Pr(someone bumped) stays below 5% for up to 106 tickets (0.040) and jumps above it at 107 (0.081). So a rule "keep the chance of bumping under 5%" gives 106 tickets, while the expected-cost rule of Example 4.6 gave 108. Different goals, different answers: the second rule cares how many are bumped and what empty seats cost, the first only whether anyone is.

R
n <- 100:115
ggplot(data.frame(n, p = 1 - pbinom(100, n, 0.9)), aes(n, p)) +
  geom_line() + geom_point() +
  geom_hline(yintercept = 0.05, linetype = "dashed") +
  labs(x = "tickets sold", y = "Pr(someone is bumped)")
Line plot of the probability that more than 100 passengers show up, against the number of…Line plot of the probability that more than 100 passengers show up, against the number of tickets sold from 100 to 115. The curve is near 0 up to 104 tickets, rises through 0.04 at 106 and 0.08 at 107, reaches 0.33 at 110, and climbs to about 0.8 at 115. A dashed line marks 5%. 0.0 0.2 0.4 0.6 0.8 100 105 110 115 tickets sold Pr(someone is bumped)

The curve rises steeply: each extra ticket beyond about 105 adds several percentage points to the chance of bumping someone.

Think About It: When the Binomial Breaks

An airline's model assumes passengers show up independently. But families and business groups travel together, and a snowstorm or a delayed connecting flight keeps many passengers away at once. How would each of these violate the BINS conditions? Would the true distribution of show-ups be more spread out or less spread out than the binomial, and why does that matter for overbooking?

Groups break independence: if one member of a family of five shows up, the others almost certainly do too, so passengers come and go in clumps. A snowstorm also breaks same p: on a bad day everyone's chance of showing up drops together. Both make large deviations from the average more common than the binomial predicts: a more spread-out distribution. An airline that used the binomial would underestimate how often a flight is badly overbooked (or half empty). This is a general lesson: independence is the assumption that most often fails, and when it fails, real-world variability is usually bigger than the model says.

Check Yourself

A juror is struck from the jury pool (for example, because of a conflict) with probability 0.25, independently. Of 12 jurors called, what is the probability that exactly 3 are struck?

In the previous question, what is the standard deviation of the number struck?

Key Takeaways

  • Bernoulli: one yes/no trial; mean p, variance p(1−p).
  • Binomial Bin(n,p): the number of successes in n independent trials with the same p. Pr(X=x)=(nx)px(1−p)n−x.
  • Mean np, variance np(1−p): found by writing X as a sum of indicators.
  • Check BINS first. Independence is the condition that fails most often in practice.
  • R: dbinom, pbinom, qbinom, rbinom.

4.5 Geometric and negative binomial: waiting for success

The binomial fixes the number of trials and counts the successes. Turn that around: keep going until you get a success, and count how long it takes. A lab tests bags one at a time until it finds a fake. A hacker tries passwords until one works. A detective interviews witnesses until one saw something.

Definition: Geometric Distribution

In a sequence of independent trials, each a success with probability p, let X be the number of failures before the first success. Then X has the geometric distribution, X∼Geom(p), with PMF Pr(X=x)=(1−p)xp,x=0,1,2,…

The formula is the multiplication rule for independent events: x failures in a row, each with probability 1−p, then one success with probability p. These add to 1 by the geometric series of Section 0.4: ∑x=0∞(1−p)xp=p⋅11−(1−p)=1.

Watch Out: Counting Failures or Counting Trials?

Books disagree on whether a geometric random variable counts the failures before the first success (values 0, 1, 2, ...) or the trials up to and including it (values 1, 2, 3, ...). They differ by exactly 1. These notes, and R's dgeom and dnbinom, count failures. If a question asks "on which trial does the first success happen?", the answer is X+1.

Theorem: Mean, Variance and Memorylessness of the Geometric

If X∼Geom(p):

  1. E[X]=1−pp and Var[X]=1−pp2; the expected number of trials up to the first success is E[X]+1=1p.
  2. Pr(X≥k)=(1−p)k for k=0,1,2,…
  3. Memorylessness. For any j,k≥0, Pr(X≥j+k∣X≥j)=Pr(X≥k).

Part 2. X≥k means the first k trials are all failures, which has probability (1−p)k by independence.

Part 3. {X≥j+k} is a subset of {X≥j}, so their intersection is {X≥j+k}, and by part 2 Pr(X≥j+k∣X≥j)=(1−p)j+k(1−p)j=(1−p)k=Pr(X≥k).

Part 1, the mean. A neat trick: for a random variable taking values 0,1,2,…, E[X]=∑k=1∞Pr(X≥k), because the value x is counted once in each of the terms k=1,…,x. So, by the geometric series, E[X]=∑k=1∞(1−p)k=1−p1−(1−p)=1−pp. The variance can be found with the moment generating function (see the interlude at the end of the chapter). ◼∎

Memorylessness says that past failures don't make a success "due". If you've already tried 50 passwords without success, the number of further tries you'll need has the same distribution as when you started. This is the gambler's fallacy of Chapter 3, made precise: independent trials have no memory.

Example 4.12: Testing Until the First Fake ★ lecture example

In a seizure, 5% of bags are fakes. A lab tests bags chosen at random, one at a time, until it finds a fake. (The seizure is large, so treat the tests as independent with p=0.05.) (a) What is the probability that the first fake is the 10th bag tested? (b) That the lab has to test more than 30 bags to find one? (c) How many bags does the lab test on average?

Name the model. Each test is a trial; "success" = finding a fake, p=0.05. Let X be the number of genuine bags (failures) before the first fake: X∼Geom(0.05).

(a) "The first fake is the 10th bag" means 9 failures then a success, X=9: Pr(X=9)=0.959×0.05≈0.0315.

(b) "More than 30 bags needed" means the first 30 are all genuine, X≥30: Pr(X≥30)=0.9530≈0.215. So more than one time in five, the lab tests 30 bags and still hasn't found a fake.

(c) The expected number of failures is 1−pp=0.950.05=19, so the expected number of bags tested, including the fake, is 19+1=20=1p.

R
dgeom(9, prob = 0.05)                  # (a)
1 - pgeom(29, prob = 0.05)             # (b): Pr(X >= 30) = 1 - Pr(X <= 29)
0.95^30                                # the same, from the formula
(1 - 0.05) / 0.05                      # (c) expected failures
output
[1] 0.03151247
[1] 0.2146388
[1] 0.2146388
[1] 19
R
ggplot(data.frame(x = 0:80, p = dgeom(0:80, 0.05)), aes(x, p)) +
  geom_col(width = 0.8) +
  geom_vline(xintercept = 19, linetype = "dashed") +
  labs(x = "genuine bags tested before the first fake", y = "probability")
Bar chart of the geometric distribution with p equal to 0.05, showing the probability of…Bar chart of the geometric distribution with p equal to 0.05, showing the probability of 0 to 80 genuine bags before the first fake. The bars start at 0.05 and decline slowly and steadily, still visible at 60 and beyond. A dashed line marks the mean of 19. 0.00 0.01 0.02 0.03 0.04 0.05 0 20 40 60 80 genuine bags tested before the first fake probability

The most likely value is 0 (the very first bag is fake), yet the mean is 19 and the tail is long: the geometric distribution is strongly right-skewed. "1 in 20" doesn't mean you'll find one within 20 tries: Pr(X≥20)=0.9520≈0.36.

Example 4.13: Collect All Six Toys ★ lecture example

A cereal brand puts one of 6 different toys in each box, each equally likely and independently. How many boxes do you expect to buy before you have the whole set?

Break the wait into stages. After you have k different toys, a new box gives a new toy with probability 6−k6. So the number of boxes needed to get from k toys to k+1 is a geometric wait for a "success" with p=6−k6, and its expected number of boxes (trials, including the success) is 1p=66−k.

toys so far, toys so far, k 0 1 2 3 4 5
chance a box is new 66 56 46 36 26 16
expected boxes for this stage 1 1.2 1.5 2 3 6

Add the stages (linearity of expectation): E[boxes]=66+65+64+63+62+61=6(1+12+13+14+15+16)=14.7. Almost 15 boxes for 6 toys, and the last toy alone takes 6 boxes on average: the final stage is the slowest, because almost every box is a duplicate. A simulation agrees and shows how variable the wait is:

R
set.seed(6)
boxes_needed <- replicate(10000, {
  seen <- c(); n <- 0
  while (length(unique(seen)) < 6) { seen <- c(seen, sample(6, 1)); n <- n + 1 }
  n
})
mean(boxes_needed)
mean(boxes_needed > 20)      # how often a collector needs more than 20 boxes
ggplot(data.frame(boxes_needed), aes(boxes_needed)) +
  geom_bar() +
  geom_vline(xintercept = 14.7, linetype = "dashed") +
  labs(x = "boxes needed to collect all 6 toys", y = "number of collectors")
output
[1] 14.6569
[1] 0.1502
Bar chart of the number of cereal boxes needed to collect all 6 toys, from 10,000…Bar chart of the number of cereal boxes needed to collect all 6 toys, from 10,000 simulated collectors. The distribution starts at 6, peaks around 11 to 13, and has a long right tail beyond 35 boxes. A dashed line marks the mean of about 14.7. 0 250 500 750 20 40 60 boxes needed to collect all 6 toys number of collectors

About 15% of collectors need more than 20 boxes. This is the coupon collector's problem. For n toys the answer is n(1+12+⋯+1n), which grows a little faster than n: collecting all 50 stickers in an album takes about 225 packs on average. Companies that sell trading cards and "loot boxes" in video games know this arithmetic very well.

Waiting for the rth success

A prosecutor may need not one confirmed fake but several. Waiting for the rth success generalizes the geometric.

Definition: Negative Binomial Distribution

In independent trials with success probability p, let X be the number of failures before the rth success. Then X has the negative binomial distribution, X∼NB(r,p), with PMF Pr(X=x)=(x+r−1x)pr(1−p)x,x=0,1,2,… and E[X]=r(1−p)p, Var[X]=r(1−p)p2. The geometric is the case r=1.

Why the formula? X=x means the rth success happens on trial x+r. So trial x+r is a success (probability p), and the first x+r−1 trials contain exactly r−1 successes and x failures, in any order. That's a binomial probability, (x+r−1x)pr−1(1−p)x. Multiply by p (independence). For the mean and variance, think of X as r geometric waits one after another: X=G1+⋯+Gr, independent, each Geom(p). Linearity gives the mean, and independence the variance.

Example 4.14: Who Wins the World Series?

In baseball's World Series, two teams play until one of them has won 4 games (a "best of seven"). Suppose the better team wins each game with probability 0.55, independently. What is the probability that the better team wins the series? What if it wins each game with probability 0.6?

Name the model. Think of the games as trials, with "success" = the better team wins. The better team wins the series if it reaches its 4th success before the other team reaches 4, that is, if it loses at most 3 games before its 4th win. With X = games lost before the 4th win, X∼NB(4,0.55), and we want Pr(X≤3).

By the formula, Pr(X=x)=(x+3x)(0.55)4(0.45)x:

losses losses x 0 1 2 3
(x+3x) 1 4 10 20
Pr(X=x) 0.0915 0.1647 0.1853 0.1668

Adding, Pr(X≤3)≈0.608.

R
pnbinom(3, size = 4, prob = 0.55)      # better team wins the series
pnbinom(3, size = 4, prob = 0.60)
p <- seq(0.5, 0.8, by = 0.05)
data.frame(game = p, series = round(pnbinom(3, 4, p), 3))
output
[1] 0.6082878
[1] 0.710208
  game series
1 0.50  0.500
2 0.55  0.608
3 0.60  0.710
4 0.65  0.800
5 0.70  0.874
6 0.75  0.929
7 0.80  0.967

(Notice that we can pretend all 7 games are played, even though the series stops early: the extra games can't change who reached 4 wins first.)

What it means. A team that wins 55% of games wins a best-of-seven series only about 61% of the time; at 60% per game, about 71%. A short series is a noisy test of which team is better: the better team loses the World Series surprisingly often, which is part of what makes it fun to watch. Longer series would sort the teams more reliably, by the Law of Large Numbers.

R
p <- seq(0.5, 0.8, by = 0.01)
ggplot(data.frame(p, series = pnbinom(3, 4, p)), aes(p, series)) +
  geom_line() +
  geom_abline(slope = 1, intercept = 0, linetype = "dashed") +
  labs(x = "Pr(better team wins one game)", y = "Pr(wins the series)")
Line plot of the probability that the better team wins a best-of-seven series, against…Line plot of the probability that the better team wins a best-of-seven series, against its probability of winning a single game, from 0.5 to 0.8. The curve starts at 0.5, passes 0.61 at 0.55 and 0.71 at 0.6, and approaches 0.97 at 0.8. A dashed diagonal line shows the single-game probability for comparison; the series curve is above it for every p above 0.5. 0.5 0.6 0.7 0.8 0.9 0.5 0.6 0.7 0.8 Pr(better team wins one game) Pr(wins the series)

The series amplifies a small edge (the curve is above the dashed diagonal), but not by much: a series is a sample of at most 7 games, and small samples are noisy.

Explore the negative binomial distribution

Move the sliders to change the parameters and watch the shape change. The red triangle marks the expected value and the red bar spans one standard deviation either side. Move x to highlight Pr(X ≤ x); the R command that computes it is shown below. Press draw a sample to simulate 200 values: the orange lines show how often each value came up, and they sit close to the bars.

Bar chart of the probability mass function for the chosen parameters, with the expected…Bar chart of the probability mass function for the chosen parameters, with the expected value and one standard deviation marked, and the bars up to x highlighted.

Think About It: Is Every Try Really Independent?

The geometric distribution assumes independent trials with the same p. For each situation, say whether that's plausible: (a) a burglar trying door handles along a street until one opens; (b) a person guessing a 4-digit PIN who never repeats a guess; (c) a basketball player shooting free throws until she misses.

(a) Doubtful: unlocked doors cluster (some streets or buildings are more careless), so after several locked doors the chance of the next being open may be lower than average, not the same. (b) No: guessing without repetition from a finite list makes each new guess more likely to succeed, since fewer possibilities remain; the wait is then uniform on 1 to 10,000, not geometric. (c) Roughly plausible, though players tire and nerves vary. The "hot hand" debate in sports statistics is exactly about whether successive shots are independent. A model's assumptions are claims about the mechanism, and checking them is part of inference.

Key Takeaways

  • Geometric Geom(p): failures before the first success; Pr(X=x)=(1−p)xp; mean (1−p)/p; expected trials 1/p.
  • Memoryless: past failures don't make success "due".
  • Negative binomial NB(r,p): failures before the rth success; mean r(1−p)/p.
  • Check whether a question counts failures or trials. R: dgeom, pgeom, dnbinom, pnbinom.

4.6 Hypergeometric: sampling without replacement

The binomial assumes every trial has the same success probability. When we sample without replacement from a small population, that fails: each item drawn changes what's left. Draw a fake bag from 2,000 with 100 fakes, and the next bag is a fake with probability 99/1999, not 100/2000. Example 3.11 handled this by counting; here is the general version.

Definition: Hypergeometric Distribution

A population of N items contains M "successes" and N−M "failures". A simple random sample of n items is drawn without replacement. Let X be the number of successes in the sample. Then X has the hypergeometric distribution, with PMF Pr(X=x)=(Mx)(N−Mn−x)(Nn), for every whole number x with 0≤x≤n, x≤M and n−x≤N−M. Its mean and variance are E[X]=nMN,Var[X]=nMN(1−MN)N−nN−1.

Why the formula? Every set of n items is equally likely: (Nn) samples. A sample with exactly x successes is made by choosing x of the M successes and n−x of the N−M failures: (Mx)(N−Mn−x) ways, by the multiplication rule. Divide (Section 3.4). Why the mean? Write X as a sum of indicators: give each of the M successes in the population an indicator for "is in the sample". By the theorem in Section 1.3, each unit is in a simple random sample with probability n/N, so each indicator has mean n/N, and linearity gives M×n/N=nM/N, even though the indicators are dependent. The variance needs Chapter 6.

Compare with the binomial, with p=M/N. The means are the same. The variance has an extra factor N−nN−1, called the finite population correction: sampling without replacement gives less variability, because the sample can't keep drawing the same kind of item. When the sample is a tiny fraction of the population, the correction is close to 1 and the two distributions are almost identical.

Theorem: Binomial Approximation to the Hypergeometric

If N and M grow with M/N→p, while n stays fixed, then the hypergeometric probabilities converge to Bin(n,p) probabilities. In practice the binomial is a good approximation when the sample is less than about 5% of the population.

Sketch. Writing out the factorials, the hypergeometric probability is (nx) times a product of n fractions: MN⋅M−1N−1⋯ for the successes and N−MN−x⋯ for the failures. As N and M grow, each fraction of the first kind tends to p and each of the second kind to 1−p, so the product tends to (nx)px(1−p)n−x. Removing a few items barely changes the proportions in a huge population. ◼∎

Example 4.15: The Lady Tasting Tea ★ lecture example

At an afternoon tea at the Rothamsted agricultural research station in England in the early 1920s, the scientist Muriel Bristol claimed she could taste whether milk had been poured into the cup before or after the tea. The statistician Ronald Fisher, who was there, proposed a test: prepare 8 cups, 4 of each kind, in random order, tell her there are 4 of each, and ask her to pick out the 4 "milk first" cups. Let X be the number of milk-first cups among the 4 she picks. If she is just guessing, (a) what is the distribution of X? (b) What is the probability she gets all 4 right? (c) Exactly 3?

Name the model. Guessing means her 4 chosen cups are a random sample of 4 from the 8, drawn without replacement. The population has N=8 cups, of which M=4 are "successes" (milk first). So X is hypergeometric with N=8, M=4, n=4.

(b) There are (84)=70 equally likely ways to pick 4 cups, and exactly one of them is the correct set: Pr(X=4)=(44)(40)(84)=170≈0.014.

(c) Exactly 3 right means choosing 3 of the 4 milk-first cups and 1 of the 4 tea-first cups: Pr(X=3)=(43)(41)(84)=1670≈0.229.

R
dhyper(0:4, m = 4, n = 4, k = 4)       # the whole PMF
choose(8, 4)
output
[1] 0.01428571 0.22857143 0.51428571 0.22857143 0.01428571
[1] 70

The full PMF is 170,1670,3670,1670,170 for x=0,…,4.

Fisher's reasoning. If she identified all 4 correctly, either she had a real ability or she was very lucky: a 1-in-70 chance. That's rare enough to take her claim seriously. But 3 out of 4 happens by pure guessing almost a quarter of the time, so it would prove nothing. Fisher used this story to open the second chapter of his book The Design of Experiments (1935), and the reasoning (how surprising would this result be if nothing but chance were at work?) is exactly the logic of the hypothesis tests in Chapter 9. According to people who were there, she got them all right.

R
d <- data.frame(x = 0:4, p = dhyper(0:4, 4, 4, 4), all = 0:4 == 4)
ggplot(d, aes(x, p, fill = all)) + geom_col(width = 0.5) +
  scale_fill_manual(values = c("grey60", "orange"), guide = "none") +
  labs(x = "milk-first cups correctly chosen, if guessing", y = "probability")
Bar chart of the hypergeometric distribution of the number of milk-first cups correctly…Bar chart of the hypergeometric distribution of the number of milk-first cups correctly identified by a guesser: 1/70 at 0, 16/70 at 1, 36/70 at 2, 16/70 at 3 and 1/70 at 4. The bar at 4, all correct, is highlighted in orange. 0.0 0.1 0.2 0.3 0.4 0.5 0 1 2 3 4 milk-first cups correctly chosen, if guessing probability

History: Ronald Fisher: A Founder, with a Troubling Side

Ronald Aylmer Fisher (1890–1962) did more than anyone else to create modern statistics. At Rothamsted he worked out how to design experiments using randomization, and he introduced or popularized variance, the analysis of variance, maximum likelihood (Chapter 8) and significance testing (Chapter 9). He was also one of the founders of modern evolutionary genetics. Medicine, agriculture and psychology still run on his methods.

Fisher was also, throughout his life, a committed eugenicist.

  • As a student he helped found the Cambridge University Eugenics Society.
  • The final chapters of his book The Genetical Theory of Natural Selection (1930) argue for policies to raise the birth rate of the "higher" social classes.
  • From 1933 he held the Galton Chair of Eugenics at University College London and edited the Annals of Eugenics.
  • In the early 1950s he disputed a UNESCO statement on race, arguing that human groups differ in their innate capacity for intellectual and emotional development.
  • Late in life he argued that the evidence linking smoking to lung cancer might not show cause and effect, while working as a consultant to the tobacco industry.

In 2020 his old Cambridge college, Gonville and Caius, removed a stained-glass window that had honoured him.

How should we hold both sets of facts? The mathematics of randomization and likelihood is correct whoever discovered it, and it has saved a great many lives. The policies Fisher argued for didn't follow from that mathematics; they came from assumptions he brought to the data. His language is under review too. In 2019 the editors of a special issue of The American Statistician, the American Statistical Association's journal, called on scientists to stop using the phrase statistically significant (an editorial view, not official ASA policy), which Fisher's work had made central (Chapter 9 explains why). Clayton goes further, suggesting that researchers report a probability distribution for the quantity of interest instead.

Example 4.16: The Drug Seizure, Revisited ★ lecture example

Of 2,000 bags, 100 are fakes, and the lab tests a random sample of 20 (Example 3.11). Let X be the number of fakes in the sample. (a) Find Pr(X=0) and Pr(X≥2). (b) Find E[X] and SD[X]. (c) How close is the binomial approximation?

Name the model. Sampling without replacement from a finite population, counting "successes" (fakes): X is hypergeometric with N=2000, M=100, n=20.

(a) By the formula, Pr(X=0)=(1000)(190020)(200020)≈0.357, as in Example 3.11. For "at least 2", use the complement of "0 or 1": Pr(X≥2)=1−Pr(X=0)−Pr(X=1). R's hypergeometric functions take the arguments (x,M,N−M,n):

R
dhyper(0, m = 100, n = 1900, k = 20)          # Pr(X = 0)
1 - phyper(1, m = 100, n = 1900, k = 20)      # Pr(X >= 2)
dbinom(0, 20, 0.05); 1 - pbinom(1, 20, 0.05)  # binomial approximation
output
[1] 0.356686
[1] 0.2640626
[1] 0.3584859
[1] 0.2641605

(R's argument names are confusing: m is the number of successes, n the number of failures, and k the sample size.)

(b) The mean and variance are E[X]=20×1002000=1,Var[X]=20×0.05×0.95×19801999≈0.941, so SD[X]≈0.970.

(c) The binomial gives Pr(X=0)=0.9520=0.358 against the exact 0.357: the sample is only 1% of the population, so the approximation is excellent, and the correction factor 19801999=0.99 barely matters.

A side-by-side comparison shows how close the two distributions are when the sample is a small fraction of the population:

R
d <- rbind(data.frame(x = 0:5, p = dhyper(0:5, 100, 1900, 20), model = "hypergeometric (exact)"),
           data.frame(x = 0:5, p = dbinom(0:5, 20, 0.05), model = "binomial approximation"))
ggplot(d, aes(x, p, fill = model)) +
  geom_col(position = "dodge", width = 0.6) +
  scale_fill_manual(values = c("orange", "grey60")) +
  labs(x = "fakes in a sample of 20", y = "probability", fill = NULL)
Paired bar chart comparing the hypergeometric distribution (20 bags from 2,000 with 100…Paired bar chart comparing the hypergeometric distribution (20 bags from 2,000 with 100 fakes) and the binomial approximation with n 20 and p 0.05, for 0 to 5 fakes. The pairs of bars are almost identical: about 0.36 at 0, 0.38 at 1, 0.19 at 2, 0.06 at 3, and very small after that. 0.0 0.1 0.2 0.3 0 2 4 fakes in a sample of 20 probability binomial approximation hypergeometric (exact)

Explore the hypergeometric distribution

Move the sliders to change the parameters and watch the shape change. The red triangle marks the expected value and the red bar spans one standard deviation either side. Move x to highlight Pr(X ≤ x); the R command that computes it is shown below. Press draw a sample to simulate 200 values: the orange lines show how often each value came up, and they sit close to the bars.

Bar chart of the probability mass function for the chosen parameters, with the expected…Bar chart of the probability mass function for the chosen parameters, with the expected value and one standard deviation marked, and the bars up to x highlighted.

Example 4.17: How Many People? Capture–recapture ★ lecture example

A city wants to estimate how many different people sleep rough on its streets, a population that is hard to count directly. In a January outreach sweep, workers record (with consent) 50 different people. In a February sweep they meet 40 people, of whom 8 were also met in January. Estimate the size of the population.

The idea. January "marks" 50 people. If February's 40 are like a random sample from the whole population of N people, the fraction of marked people in February's sample should be about the fraction of marked people in the population: 840≈50N⇒N̂=50×408=250. This is the Lincoln–Petersen estimator, first used for fish and wildlife, and now for hidden human populations (drug users, victims of trafficking, war casualties).

The model behind it. If the population has N people, of whom M=50 are marked, the number X of marked people in a random sample of n=40 is hypergeometric. For each possible N, we can ask how probable the observed X=8 would be, and choose the N that makes it most probable:

R
N <- 90:800
lik <- dhyper(8, m = 50, n = N - 50, k = 40)
N[which.max(lik)]
ggplot(data.frame(N, lik), aes(N, lik)) +
  geom_line() +
  geom_vline(xintercept = 250, linetype = "dashed") +
  labs(x = "assumed population size N", y = "Pr(8 marked in sample)")
output
[1] 250
Line plot of the probability of seeing exactly 8 marked people in a sample of 40, against…Line plot of the probability of seeing exactly 8 marked people in a sample of 40, against the assumed population size N from 90 to 800. The curve rises to a peak at N equal to 250, marked with a dashed line, then falls slowly with a long right tail. 0.00 0.05 0.10 0.15 200 400 600 800 assumed population size N Pr(8 marked in sample)

The peak is at N=250 (tied, in fact, with N=249), the same answer as before. Choosing the parameter value that makes the observed data most probable is called maximum likelihood, and it is the main estimation method of Chapter 8. Notice the long right tail: populations of 400 or more are not wildly implausible, so 250 comes with a lot of uncertainty.

Critical thinking: the assumptions. The calculation assumes the population doesn't change between sweeps (no one arrives or leaves), and that every person is equally likely to be met in February whether or not they were met in January. Both are doubtful. People who are easy to find in January are probably easy to find in February too; then February's sample over-represents marked people, the fraction 8/40 is too high, and N̂ is too low. Real studies use several sweeps and more elaborate models to deal with this.

Think About It: Who Is in the Sample?

Capture–recapture (Example 4.17) assumes that being "caught" the first time doesn't change your chance of being caught again. Think of a population of drug users estimated from two lists: people treated in hospitals and people arrested. Why might the assumption fail, and in which direction would the estimate be wrong?

The two lists are not independent samples: people with severe addiction are more likely both to be hospitalized and to be arrested, so the same people appear on both lists more often than chance would suggest. The overlap (8 people in Example 4.17) is then too big, and since the estimate divides by the overlap, it is too small: the hidden population is larger than the estimate. Researchers who use this method (to count drug users, victims of trafficking, or casualties of war) try to use lists that are as unrelated as possible, and use three or more lists to detect dependence. This is inference about a mechanism you can't see, and the answer is only as good as the sampling assumptions.

Key Takeaways

  • Hypergeometric: successes in a sample of n drawn without replacement from N items with M successes; Pr(X=x)=(Mx)(N−Mn−x)/(Nn).
  • Mean nM/N, like the binomial; variance smaller by the factor (N−n)/(N−1).
  • If the sample is under about 5% of the population, the binomial with p=M/N is an excellent approximation.
  • R: dhyper(x, m, n, k) with m successes, n failures, k drawn.

Lecture 11 — The Poisson model and choosing a model

4.7 Poisson: counting rare events

Many chances, each small

How many 911 calls arrive at a dispatch desk in an hour? How many typos are on a page, burglaries on a block in a year, cases of a rare disease in a county? In each case there are a huge number of opportunities for the event (thousands of people who might call), each with a tiny probability, independently. The count is binomial in principle, but we don't know n or p separately: we only know the average rate.

Here is the idea that leads to the Poisson distribution. Suppose calls arrive at an average rate of λ=4.5 per hour. Split the hour into n short slots, so short that at most one call can arrive in each. Each slot gets a call with probability λ/n, independently, so the number of calls is Bin(n,λ/n), with mean n×λ/n=λ whatever n is. Now let the slots get shorter and shorter.

From binomial to Poisson

The idea from Section 4.7: split the hour into n slots, each with probability λ/n of an arrival. The bars are Bin(n, λ/n); the dots are Pois(λ). Slide n from 5 (slots of 12 minutes) upwards and watch the bars settle onto the dots.

Bars of a binomial distribution with n slots and success probability lambda over n…Bars of a binomial distribution with n slots and success probability lambda over n, overlaid with dots for the Poisson distribution with rate lambda.

Theorem: The Poisson Limit of the Binomial

Fix λ>0. If Xn∼Bin(n,λ/n), then for each x=0,1,2,…, Pr(Xn=x)→e−λλxx!as n→∞.

Write out the binomial probability with p=λ/n and rearrange into three factors: (nx)(λn)x(1−λn)n−x=λxx!⋅n(n−1)⋯(n−x+1)nx⋅(1−λn)n(1−λn)−x.(nx)(λn)x(1−λn)n−x=λxx!⋅n(n−1)⋯(n−x+1)nx⋅(1−λn)n(1−λn)−x. As n→∞, with x fixed:

  • n(n−1)⋯(n−x+1)nx=1⋅(1−1n)⋯(1−x−1n)→1;
  • (1−λn)n→e−λ, a standard limit from calculus;
  • (1−λn)−x→1.

So the product tends to λxx!e−λ. ◼∎

Definition: Poisson Distribution

A random variable X has the Poisson distribution with rate (or mean) λ>0, written X∼Pois(λ), if Pr(X=x)=e−λλxx!,x=0,1,2,…

These probabilities add to 1 by the exponential series (Example 0.2): that is exactly the calculation we did in Chapter 0.

Theorem: Mean and Variance of the Poisson

If X∼Pois(λ), then E[X]=λ and Var[X]=λ.

Mean. The x=0 term is zero; for x≥1, cancel x against x! and substitute y=x−1: E[X]=∑x=1∞xe−λλxx!=λ∑x=1∞e−λλx−1(x−1)!=λ∑y=0∞e−λλyy!=λ×1. Variance. The same trick with x(x−1) cancels two factors: E[X(X−1)]=λ2∑y=0∞e−λλyy!=λ2. So E[X2]=E[X(X−1)]+E[X]=λ2+λ, and Var[X]=λ2+λ−λ2=λ. ◼∎

Mean equals variance is the Poisson's fingerprint. It explains the insecticide data of Chapter 2 (Exercise 2.10), where counts with bigger averages were also more spread out. And it gives a quick check of whether real counts could be Poisson: compare their sample mean and variance.

Example 4.18: Death by Horse Kick ★ lecture example

In 1898 the Russian–German statistician Ladislaus Bortkiewicz published the number of soldiers killed by horse kicks in 10 corps of the Prussian cavalry over 20 years (1875–1894): 200 "corps-years" in all.

deaths in a corps-year, deaths in a corps-year, x 0 1 2 3 4 5+
number of corps-years 109 65 22 3 1 0

(a) Estimate λ, the average number of deaths per corps-year. (b) Compare the observed counts with what a Poisson distribution with that λ predicts. (c) Compare the sample mean and variance.

Why might Poisson fit? Each corps had many soldiers, each with a tiny chance of a fatal kick in a year, more or less independently: many chances, each small.

(a) The total number of deaths is 0(109)+1(65)+2(22)+3(3)+4(1)=65+44+9+4=122, over 200 corps-years, so λ̂=122200=0.61.

(b) The expected number of corps-years with x deaths is 200×Pr(X=x) for X∼Pois(0.61). By hand for x=0 and x=1: 200×e−0.61=200×0.5434≈108.7,200×e−0.61×0.61≈66.3.

R
x <- 0:4
observed <- c(109, 65, 22, 3, 1)
lambda <- sum(x * observed) / 200
lambda
expected <- 200 * dpois(x, lambda)
round(data.frame(x, observed, expected), 1)
output
[1] 0.61
  x observed expected
1 0      109    108.7
2 1       65     66.3
3 2       22     20.2
4 3        3      4.1
5 4        1      0.6
R
ggplot(data.frame(x, observed, expected), aes(x, observed)) +
  geom_col(width = 0.5) +
  geom_point(aes(y = expected), colour = "orange", size = 3.5) +
  labs(x = "deaths in a corps-year", y = "number of corps-years")
Bar chart comparing observed and Poisson-expected numbers of corps-years with 0 to 4…Bar chart comparing observed and Poisson-expected numbers of corps-years with 0 to 4 horse-kick deaths. Observed bars are 109, 65, 22, 3 and 1; orange dots for the Poisson expectations are 108.7, 66.3, 20.2, 4.1 and 0.6, sitting almost on top of the bars. 0 30 60 90 0 1 2 3 4 deaths in a corps-year number of corps-years

The agreement is remarkable: 109 vs 108.7, 65 vs 66.3, 22 vs 20.2, 3 vs 4.1, 1 vs 0.6.

(c) The sample variance of the 200 counts (computed as in Chapter 2) is 0.611, almost exactly the mean 0.61, as a Poisson distribution predicts.

R
deaths <- rep(x, observed)        # the 200 individual counts
c(mean = mean(deaths), var = var(deaths))
output
     mean       var 
0.6100000 0.6109548 

Bortkiewicz called this the law of small numbers: rare events, scattered over many independent opportunities, follow the Poisson distribution, even something as grim and haphazard as a horse kick.

The two goals. The Poisson model predicts how many corps-years should have 0, 1, 2, ... deaths if kicks are random and independent. Comparing that prediction with the data is a piece of inference: the close agreement is evidence that nothing more systematic (a particularly dangerous corps, a bad year) was going on.

Example 4.19: Were the Flying Bombs Aimed? ★ lecture example

In 1944 and 1945 Germany fired V-1 flying bombs at London. People in the city noticed that some districts seemed to be hit again and again while others were spared, and wondered whether the bombs could be aimed at particular targets. After the war, the actuary R. D. Clarke divided an area of south London into 576 small squares of a quarter of a square kilometre each, and counted the hits in each square. There were 537 hits in all:

hits in a square, hits in a square, x 0 1 2 3 4 5 or more
number of squares 229 211 93 35 7 1

If the bombs fell at random, with no aiming, the number of hits per square should be Poisson. Does the Poisson model fit?

Why Poisson if random? Each of the 537 bombs had a small chance (1 in 576) of landing in any particular square, independently of the others: many chances, each small. So the hits in a square would be close to Bin(537,1576), which is approximately Pois(λ) with λ=537576≈0.932 hits per square.

Expected counts. The expected number of squares with x hits is 576×Pr(X=x). For x=0: 576×e−0.932≈576×0.394=226.7.

R
lambda <- 537 / 576
observed <- c(229, 211, 93, 35, 7, 1)
expected <- 576 * c(dpois(0:4, lambda), 1 - ppois(4, lambda))   # last group: 5 or more
data.frame(hits = c("0", "1", "2", "3", "4", "5+"), observed, expected = round(expected, 1))
output
  hits observed expected
1    0      229    226.7
2    1      211    211.4
3    2       93     98.5
4    3       35     30.6
5    4        7      7.1
6   5+        1      1.6
R
d <- data.frame(hits = factor(c("0", "1", "2", "3", "4", "5+"), levels = c("0", "1", "2", "3", "4", "5+")),
                observed, expected)
ggplot(d, aes(hits, observed)) +
  geom_col(width = 0.5) +
  geom_point(aes(y = expected), colour = "orange", size = 3.5) +
  labs(x = "hits in a square", y = "number of squares")
Bar chart comparing observed and Poisson-expected numbers of London squares with 0 to 5…Bar chart comparing observed and Poisson-expected numbers of London squares with 0 to 5 or more V-1 hits. Observed bars are 229, 211, 93, 35, 7 and 1; orange dots for the Poisson expectations are 226.7, 211.4, 98.5, 30.6, 7.1 and 1.6, almost exactly on the bars. 0 50 100 150 200 0 1 2 3 4 5+ hits in a square number of squares

The fit is excellent: 229 vs 226.7, 211 vs 211.4, 93 vs 98.5, 35 vs 30.6, 7 vs 7.1, 1 vs 1.6. The clusters that Londoners noticed are exactly what random scattering produces: with 576 squares, about 39 should get 3 or more hits by chance alone. The data give no evidence that the bombs could be aimed at specific districts.

The lesson. Randomness is clumpy (remember the coin-faking widget in Section 1.6). People see patterns, such as "cancer clusters", "hot streaks" and "crime waves", in data that are perfectly consistent with chance. Before explaining a cluster, compare it with what the Poisson distribution says chance alone would produce.

Source: R. D. Clarke (1946), "An application of the Poisson distribution", Journal of the Institute of Actuaries 72, 481.

Rates over time and space

The Poisson rate scales with the size of the window. If 911 calls arrive at 4.5 per hour, then in 20 minutes they arrive at 4.5×2060=1.5 per 20 minutes, and in a day at 4.5×24=108 per day. Events that occur one at a time, independently, at a constant average rate, form a Poisson process: the number of events in any window of length t is Pois(λt), and counts in non-overlapping windows are independent.

Example 4.20: Calls at a Dispatch Desk ★ lecture example

A 911 dispatch desk receives calls at an average rate of 4.5 per hour during a weekday afternoon, and calls arrive independently. (a) What is the probability of no calls in an hour? (b) The desk has two dispatchers, who can comfortably handle up to 7 calls an hour. What is the probability of 8 or more calls in an hour? (c) What is the probability of a 20-minute stretch with no calls at all?

Name the model. Many potential callers, each unlikely to call in a given hour, independently, at an average rate: X∼Pois(4.5) calls per hour.

(a) Pr(X=0)=e−4.5≈0.0111: about 1 hour in 90.

(b) Pr(X≥8)=1−Pr(X≤7), a sum of 8 terms, so use R:

R
dpois(0, lambda = 4.5)              # (a)
1 - ppois(7, lambda = 4.5)          # (b) Pr(X >= 8)
dpois(0, lambda = 4.5 * 20 / 60)    # (c) a 20-minute window: rate 1.5
round(dpois(0:12, 4.5), 3)          # the PMF
output
[1] 0.011109
[1] 0.08658647
[1] 0.2231302
 [1] 0.011 0.050 0.112 0.169 0.190 0.171 0.128 0.082 0.046 0.023 0.010
[12] 0.004 0.002

So Pr(X≥8)≈0.087: in roughly one afternoon hour in 11, the desk is overloaded. A manager deciding on staffing would weigh that against the cost of a third dispatcher (an expected-loss calculation again).

(c) In 20 minutes the rate is 4.5×13=1.5, so Pr(no calls)=e−1.5≈0.223.

R
d <- data.frame(x = 0:12, p = dpois(0:12, 4.5), busy = 0:12 >= 8)
ggplot(d, aes(x, p, fill = busy)) +
  geom_col(width = 0.6) +
  scale_fill_manual(values = c("grey60", "orange"), labels = c("up to 7", "8 or more")) +
  labs(x = "calls in an hour", y = "probability", fill = NULL)
Bar chart of the Poisson distribution with mean 4.5, for 0 to 12 calls in an hourBar chart of the Poisson distribution with mean 4.5, for 0 to 12 calls in an hour. The bars rise to a peak at 4 calls (about 0.19), with 3 and 5 nearly as tall, then fall. Bars for 8 or more calls are shaded orange, together about 0.09 of the probability. 0.00 0.05 0.10 0.15 0 4 8 12 calls in an hour probability up to 7 8 or more

Explore the Poisson distribution

Move the sliders to change the parameters and watch the shape change. The red triangle marks the expected value and the red bar spans one standard deviation either side. Move x to highlight Pr(X ≤ x); the R command that computes it is shown below. Press draw a sample to simulate 200 values: the orange lines show how often each value came up, and they sit close to the bars.

Bar chart of the probability mass function for the chosen parameters, with the expected…Bar chart of the probability mass function for the chosen parameters, with the expected value and one standard deviation marked, and the bars up to x highlighted.

Causal Inference: Regression to the Mean: Hot Spots That Cool Down on Their Own

A police department identifies the 10 blocks with the most burglaries last year as "hot spots" and sends extra patrols. This year, burglaries on those blocks fall by 25%. Did the patrols work?

Not necessarily. Counts like burglaries vary by Poisson chance even when nothing changes. A block that had an unusually high count last year was probably partly unlucky, and next year its luck is likely to be closer to average, patrols or no patrols. Choosing units because their outcome was extreme guarantees that, on average, they'll look less extreme next time. This is regression to the mean, an effect Francis Galton called "regression towards mediocrity" in 1885–86 (the history box in Section 5.3 explains where it came from). In the simulation below, the "patrols" do nothing at all.

Hot spots that cool down on their own

A city has 100 blocks. Every block has the same true rate of burglaries, λ per year, so the counts differ only by Poisson chance. After year 1, the city labels the blocks with the highest counts as "hot spots" and sends extra patrols there. The patrols do nothing at all in this simulation. Press simulate and compare the hot spots' counts in year 1 and year 2.

Dot plot of burglary counts for 100 blocks in year 1 and year 2, with lines joining each…Dot plot of burglary counts for 100 blocks in year 1 and year 2, with lines joining each hot-spot block's two counts.

The selection is the problem: last year's count caused the block to be chosen, and last year's count is related to this year's only through the block's true rate. A fair test needs a comparison group: randomly choose which hot spots get the patrols (Chapter 1), and compare treated and untreated hot spots in the same year. Real hot-spot policing studies that did exactly this did find genuine (if smaller) effects; studies that only compared before and after could not tell them apart from regression to the mean.

History: Poisson, Bortkiewicz and the Law of Small Numbers

Siméon-Denis Poisson derived the distribution in 1837, as the limit of the binomial, in a book on the probability of judgments in criminal and civil cases: he wanted to know how often juries would convict the innocent. It attracted little attention until Ladislaus Bortkiewicz showed in Das Gesetz der kleinen Zahlen (The Law of Small Numbers, 1898) how well it described rare events in large populations, from horse kicks to child suicides. Today it describes radioactive decay, network traffic, insurance claims and mutations in DNA.

Think About It: Randomness or a Cause?

A town of 20,000 people has 9 cases of a rare childhood cancer in five years, when the national rate would predict about 3. Residents suspect a chemical plant. Using Poisson reasoning, explain why this is genuinely surprising for this town, but why it might not be surprising that some town in the country has a cluster like this. What would you want to know next?

For this town, the count would be about Pois(3), and Pr(X≥9)= 1 - ppois(8, 3) ≈0.004: very unusual. But there are thousands of towns of this size, and among, say, 5,000 towns we'd expect about 5000×0.004≈20 to have such a cluster by chance alone (the birthday problem and Paul the octopus again). The cluster was noticed because it was extreme, so its surprise value is overstated. Next steps: was the cluster noticed before or after looking at many towns? Is there a plausible mechanism (exposure to a specific chemical linked to this cancer)? Do cases concentrate near the plant, and did they begin after it opened? Inference about causes needs more than an unusual count.

Key Takeaways

  • Poisson Pois(λ): counts of rare events with many independent opportunities; Pr(X=x)=e−λλx/x!.
  • It is the limit of Bin(n,λ/n) as n→∞.
  • Mean = variance = λ. Rates scale with the window: λt in a window of length t.
  • Units chosen for extreme counts tend to look less extreme next time: regression to the mean.
  • R: dpois, ppois, qpois, rpois.

4.8 Choosing the right model

The hardest part of a problem is usually not the arithmetic but deciding which distribution fits. Here are the five named distributions side by side.

Start with the mechanism: what is being counted, and how are the trials run? This flowchart asks the questions in order.

A flowchart for choosing a discrete distributionA flowchart for choosing a discrete distribution. Start: what are you counting? If successes in a fixed number of trials: are the trials independent with the same probability? If yes, binomial. If the draws are without replacement from a small population, hypergeometric. If you are counting failures before a success: before the first success, geometric; before the r-th success, negative binomial. If you are counting events in a fixed stretch of time or space with no fixed number of trials, Poisson. If the outcomes are equally likely values, discrete uniform.What are you counting?successes inn fixed trialsfailures beforea successevents in atime or spacedrawn withoutreplacement froma small population?binomialhypergeometricgeometricneg. binomialPoissonnoyesfirstr-thrare,independentAll equally likely values (a die, a lottery draw)? Discrete uniform.
Start at the top and answer each question about the mechanism. The question is always what is being counted, and how the trials are run.
distribution the story values
Bin(n,p) successes in n independent trials, same p 0,…,n
Geom(p) failures before the 1st success 0,1,2,…
NB(r,p) failures before the rth success 0,1,2,…
hypergeometric successes in n drawn without replacement from N items with M successes 0,…,n
Pois(λ) count of rare events at average rate λ 0,1,2,…
distribution mean variance PMF in R
Bin(n,p) np np(1−p) dbinom(x, n, p)
Geom(p) 1−pp 1−pp2 dgeom(x, p)
NB(r,p) r(1−p)p r(1−p)p2 dnbinom(x, r, p)
hypergeometric nMN nMN(1−MN)N−nN−1 dhyper(x, M, N-M, n)
Pois(λ) λ λ dpois(x, lambda)

Idea: Algorithm: Which Distribution?

  1. What is being counted? Write $X = $ "the number of ...". If it isn't a count, it isn't one of these.
  2. Is there a fixed number of trials?
    • Yes, drawn with replacement or from a huge population, independent, same p: binomial.
    • Yes, drawn without replacement from a small, known population: hypergeometric.
  3. Are we waiting for something? Counting failures until the 1st success: geometric; until the rth: negative binomial.
  4. Is there only a rate, with no natural "number of trials", for events in time or space? Poisson.
  5. Check the assumptions, especially independence, and say which ones are doubtful.

Example 4.21: Which Distribution? ★ lecture example

For each situation, define X, name its distribution with parameters, and compute the probability asked for.

  1. A detective calls witnesses from a list; each, independently, has information with probability 0.2. What is the probability the first 4 calls find nothing and the 5th succeeds?
  2. A jury of 6 is chosen at random from a pool of 50 people, of whom 5 are retired police officers. What is the probability the jury includes exactly 2 of them?
  3. A forensic lab receives an average of 2.5 urgent requests per day, arriving independently. What is the probability of 5 or more on a given day?
  4. Of a company's emails, 2% are phishing attempts. In a random sample of 50 emails from its huge inbox, what is the probability there are none?
  1. We wait for the first success: X = failed calls before the first useful witness ∼Geom(0.2). "First 4 fail, 5th succeeds" is X=4: Pr(X=4)=0.84×0.2=0.0819.

  2. A fixed sample drawn without replacement from a small population: X = officers on the jury, hypergeometric with N=50, M=5, n=6. Pr(X=2)=(52)(454)(506)≈0.0938. (The sample is 12% of the population, so the binomial would not be a safe approximation here.)

  3. Events at a rate, with no fixed number of trials: X∼Pois(2.5). Pr(X≥5)=1−Pr(X≤4)≈0.109.

  4. A fixed number of emails from a huge population, independent, same p: X∼Bin(50,0.02). Pr(X=0)=0.9850≈0.364. (A Poisson with λ=50×0.02=1 gives e−1=0.368: close, as the limit theorem promises.)

R
dgeom(4, 0.2)                                  # 1
dhyper(2, m = 5, n = 45, k = 6)                # 2
1 - ppois(4, 2.5)                              # 3
dbinom(0, 50, 0.02); dpois(0, 1)               # 4, and its Poisson approximation
output
[1] 0.08192
[1] 0.09376239
[1] 0.108822
[1] 0.3641697
[1] 0.3678794

Check Yourself

Key Takeaways

  • Start by writing $X = $ "the number of ...".
  • Fixed trials with replacement: binomial; without replacement from a small population: hypergeometric; waiting: geometric or negative binomial; a rate: Poisson.
  • Every model rests on assumptions, usually independence. Name them, and ask what happens if they fail.

Prediction and inference in this chapter

Every distribution in this chapter is a model of a mechanism with a few parameters, and every example used it in one of two directions.

Chapters 8 and 9 turn these informal arguments into estimates with margins of error and into formal tests. They will need one more ingredient first: how averages of random variables behave, which is the subject of Chapters 6 and 7.

4.9 Interludes

Interlude (Optional): Moment Generating Functions

The moment generating function (MGF) of a random variable X is MX(t)=E[etX]=∑xetxp(x), for the values of t where the sum is finite. It looks like an odd thing to compute, but it packs all the moments E[X],E[X2],… into one function. Expanding etX=1+tX+t2X22!+⋯ and taking expectations term by term gives MX(t)=1+tE[X]+t22!E[X2]+⋯, so differentiating and setting t=0 picks out the moments: MX′(0)=E[X] and MX″(0)=E[X2].

Three examples.

  • Bernoulli: M(t)=(1−p)e0+pet=1−p+pet.
  • Binomial: X is a sum of n independent Bernoullis, and for independent random variables E[et(X+Y)]=E[etX]E[etY] (Chapter 6), so M(t)=(1−p+pet)n. Differentiating, M′(0)=n(1−p+p)n−1p=np.
  • Poisson: M(t)=∑xetxe−λλxx!=e−λ∑x(λet)xx!=e−λeλet=eλ(et−1).

Two powerful facts. First, an MGF (when it exists near t=0) determines the distribution uniquely. Second, the MGF of a sum of independent random variables is the product of their MGFs. Together they give slick proofs. For example, if X∼Pois(λ) and Y∼Pois(μ) are independent, then MX+Y(t)=eλ(et−1)eμ(et−1)=e(λ+μ)(et−1), which is the MGF of Pois(λ+μ). So independent Poisson counts add up to a Poisson count: calls to two separate desks, at rates 4.5 and 3 per hour, total Pois(7.5).

Why it matters: MGFs are the main tool for proving the Central Limit Theorem in Chapter 7.

Interlude (Optional): Entropy: How Surprising Is a Random Variable?

Section 2.6 met Shannon's entropy, a measure of how unpredictable a categorical variable is. It applies to any discrete random variable: H(X)=−∑xp(x)log2p(x)bits. The quantity −log2p(x) is the surprise of seeing the value x: a sure thing (p=1) carries 0 bits of surprise, a fair coin flip 1 bit, and a one-in-a-million event about 20 bits. Entropy is the expected surprise, E[−log2p(X)], computed with the expectation rule of Section 4.2.

For a Bernoulli trial, H=−plog2p−(1−p)log2(1−p):

R
p <- seq(0.001, 0.999, by = 0.001)
H <- -p * log2(p) - (1 - p) * log2(1 - p)
ggplot(data.frame(p, H), aes(p, H)) + geom_line() +
  labs(x = "success probability p", y = "entropy H (bits)")
Curve of the entropy of a Bernoulli random variable against p from 0 to 1Curve of the entropy of a Bernoulli random variable against p from 0 to 1. It is 0 at p equals 0 and at p equals 1, and rises symmetrically to a maximum of 1 bit at p equals one half. 0.00 0.25 0.50 0.75 1.00 0.00 0.25 0.50 0.75 1.00 success probability p entropy H (bits)

It is largest, 1 bit, at p=12, and zero when the outcome is certain, just like the variance p(1−p), though entropy and variance are not the same thing: entropy doesn't care what the values are, only how probable they are.

Shannon proved that H(X) is the smallest possible average number of bits needed to record outcomes of X, which is the foundation of every compression format from ZIP to MP3. And a password chosen uniformly from mk possibilities has entropy klog2m bits: about 52 bits for 8 characters from 94 symbols (Example 3.7). Security experts measure password strength in exactly these bits, and a password people actually choose has far fewer.

Why it matters: entropy turns "how uncertain?" into a number, and underlies information theory, compression, cryptography and the cross-entropy loss used to train classifiers.

Bayesian Inference: Learning a Success Probability

In Example 4.10 we knew the false-positive rate p. Usually we don't, and must learn it from data. The Bayesian approach treats the unknown p like the suspects in Chapter 3's detective story. Suppose p could be any of 0,0.1,0.2,…,1, all equally plausible at first (the prior). We then see 7 successes in 10 independent trials. For each candidate value of p, the likelihood of the data is the binomial probability (107)p7(1−p)3. Multiply prior by likelihood and rescale:

R
p_grid <- seq(0, 1, by = 0.1)
prior <- rep(1 / 11, 11)
likelihood <- dbinom(7, size = 10, prob = p_grid)
posterior <- prior * likelihood / sum(prior * likelihood)
round(posterior, 3)
d <- rbind(data.frame(p = p_grid, prob = prior, which = "prior"),
           data.frame(p = p_grid, prob = posterior, which = "posterior, 7 of 10"))
d$which <- factor(d$which, levels = c("prior", "posterior, 7 of 10"))
ggplot(d, aes(p, prob)) + geom_col(width = 0.06) + facet_wrap(~ which) +
  labs(x = "candidate value of p", y = "probability")
output
 [1] 0.000 0.000 0.001 0.010 0.047 0.129 0.236 0.293 0.221 0.063 0.000
Two bar charts side by side over the candidate values of p from 0 to 1 in steps of 0.1Two bar charts side by side over the candidate values of p from 0 to 1 in steps of 0.1. Left, the prior: all bars equal at about 0.09. Right, the posterior after 7 successes in 10 trials: bars near zero below 0.4, rising to a peak of 0.29 at p equals 0.7, then 0.22 at 0.8, 0.06 at 0.9, and 0 at 1. prior posterior, 7 of 10 0.00 0.25 0.50 0.75 1.00 0.00 0.25 0.50 0.75 1.00 0.0 0.1 0.2 0.3 candidate value of p probability

The posterior piles up around 0.7, the observed fraction, but still gives real weight to 0.6 and 0.8: ten trials can't pin p down exactly. More data would narrow it further. Chapter 5 replaces the grid of 11 candidates with every value between 0 and 1, which leads to the beta distribution.

4.10 Exercises

Each exercise has a hint and an answer. Start every word problem by writing $X = $ "the number of ..." and naming its distribution.

Exercises

  1. A PMF by hand. Roll two fair dice and let M be the larger of the two numbers. (a) Find the PMF of M by counting outcomes. (b) Find E[M]. (c) Find Pr(M≤3) using the CDF.

    Use the 6 × 6 grid (the random-variable widget in Section 3.8 has a "larger of the two dice" option). How many of the 36 outcomes have a maximum of exactly 1? Of exactly 2? Look for the pattern 2m−1.

    (a) Pr(M=m)=2m−136 for m=1,…,6: that is 136,336,536,736,936,1136. (b) E[M]=1+6+15+28+45+6636=16136≈4.47. (c) F(3)=1+3+536=936=0.25; equivalently both dice are at most 3, (36)2.

  2. Expected value and variance. A random variable takes the values −1, 0 and 2 with probabilities 0.3, 0.5 and 0.2. Find E[X], Var[X], E[5−2X] and SD[5−2X].

    Compute E[X] and E[X2] first, then use the shortcut formula and the rules for aX+b.

    E[X]=−0.3+0+0.4=0.1; E[X2]=0.3+0+0.8=1.1; Var[X]=1.1−0.01=1.09. E[5−2X]=5−0.2=4.8; SD[5−2X]=21.09≈2.09.

  3. Insurance. A phone insurance policy costs $120 a year. In a year, 4% of phones are lost or stolen (the insurer pays $900) and another 10% are damaged (the insurer pays $250). (a) Find the insurer's expected profit per policy. (b) Find the standard deviation of its profit. (c) Explain why the insurer cares about the expected value but a customer might not.

    The insurer's profit takes three values: 120, 120−900 and 120−250. Write its PMF, then compute E and SD as in Examples 4.5 and 4.8.

    Profit 120 (prob 0.86), −780 (0.04), −130 (0.10). (a) E=103.2−31.2−13=$59. (b) E[profit2]=0.86×14400+0.04×608400+0.10×16900=12384+24336+1690=38410, so Var=38410−592=34929 and SD≈$187. (c) The insurer sells thousands of policies, so by the Law of Large Numbers its average profit per policy will be very close to $59. A customer buys one policy and faces one outcome; they pay $59 on average to avoid a possible $900 loss they might not be able to afford.

  4. Binomial. A fingerprint examiner makes an error on 3% of comparisons, independently. In a week she makes 40 comparisons. (a) What is the probability of no errors? (b) Of at least 2 errors? (c) What are the mean and standard deviation of the number of errors? (d) Is independence plausible here? Explain.

    X∼Bin(40,0.03). For (b), Pr(X≥2)=1−Pr(X≤1), which is 1 - pbinom(1, 40, 0.03) in R.

    (a) 0.9740≈0.296. (b) 1−0.296−40(0.03)(0.9739)≈1−0.296−0.366=0.338. (c) Mean 1.2, SD 40×0.03×0.97≈1.08. (d) Doubtful: errors may cluster, for example on difficult partial prints, at the end of a long day, or on cases with misleading context information, so one error makes others more likely.

  5. Geometric. A password-guessing program tries passwords from a list of common passwords in random order, and each guess independently has a 1-in-50 chance of being right for a given account. (a) What is the expected number of wrong guesses before success? (b) What is the probability it needs more than 100 guesses in total? (c) The program has already made 100 wrong guesses. What is the probability it needs more than another 100?

    X∼Geom(0.02) counts wrong guesses. "More than 100 guesses in total" means the first 100 are all wrong. For (c), use memorylessness.

    (a) 0.98/0.02=49 wrong guesses (50 guesses in all, on average). (b) Pr(X≥100)=0.98100≈0.133. (c) By memorylessness, also 0.98100≈0.133: the 100 failures so far don't make success any closer. (In reality, guessing without repeating passwords from a finite list isn't memoryless, but the model says each guess is a fresh independent chance.)

  6. Hypergeometric. An evidence locker holds 30 bags, of which 8 have been tampered with. An auditor inspects 5 bags chosen at random. (a) What is the probability she finds no tampered bags? (b) At least one? (c) Compare (a) with the binomial approximation and explain the difference.

    N=30, M=8, n=5. In R: dhyper(0, m = 8, n = 22, k = 5). The binomial would use p=8/30.

    (a) (225)/(305)=26334/142506≈0.185. (b) 1−0.185=0.815. (c) The binomial gives (22/30)5≈0.212, noticeably higher. The sample is 1/6 of the population, and each untampered bag drawn makes the next draw more likely to be tampered, so missing every tampered bag is less likely than the binomial suggests.

  7. Poisson. A website receives login attacks at an average rate of 3 per minute, independently. (a) What is the probability of no attacks in a given minute? (b) Of more than 6 in a minute? (c) Of at least 10 in a 2-minute window?

    One minute: Pois(3). Two minutes: Pois(6). "More than 6" is 1−Pr(X≤6).

    (a) e−3≈0.050. (b) 1 - ppois(6, 3) ≈0.034. (c) 1 - ppois(9, 6) ≈0.084.

  8. Poisson approximation. A rare blood type occurs in 0.4% of people. A blood drive collects 500 donations. Find the probability of at least 3 donations with the rare type (a) exactly, with the binomial, and (b) with the Poisson approximation. Why is the approximation good here?

    Binomial: Bin(500,0.004). Poisson: λ=np.

    (a) 1 - pbinom(2, 500, 0.004) ≈0.323. (b) λ=2; 1 - ppois(2, 2) ≈0.323. The approximation is excellent because n is large and p is small: many chances, each rare, exactly the setting of the Poisson limit theorem.

  9. Is it Poisson? R's InsectSprays counts insects on plots. For spray C, the 12 counts are 0, 1, 7, 2, 3, 1, 2, 1, 3, 0, 1, 4. (a) Compute the sample mean and variance. (b) Is a Poisson model plausible? (c) Using a Poisson with λ equal to the sample mean, how many of the 12 plots would you expect to have 0 insects? Compare with the data.

    x <- InsectSprays$count[InsectSprays$spray == "C"], then mean(x) and var(x). For (c), compute 12 * dpois(0, mean(x)).

    (a) Mean 25/12≈2.08, variance ≈3.90. (b) The variance is nearly twice the mean, so the counts are more variable than a Poisson (called overdispersion), largely because of the plot with 7 insects; with only 12 counts, though, the evidence is weak. (c) 12e−2.08≈1.5 plots expected, and 2 were observed: reasonably close.

  10. Linearity with indicators. At a party, 30 guests check their coats, and the coats are returned at random. (a) What is the expected number of guests who get their own coat back? (b) A city has 200 intersections, and each has a camera that works on a given day with probability 0.97, not necessarily independently. What is the expected number of working cameras, and why don't you need independence?

    Write each count as a sum of indicators, as in Example 4.7. Linearity of expectation doesn't require independence.

    (a) Each guest gets their own coat with probability 130, so the expected number is 30×130=1. (b) 200×0.97=194. E[I1+⋯+I200]=E[I1]+⋯+E[I200] holds whatever the dependence; independence would matter for the variance (for example, a citywide power cut would knock out many cameras at once).

  11. Which model? For each, define X, name the distribution and its parameters, and state one assumption that might fail. (a) The number of jurors, out of 12, who have served on a jury before, if 30% of the jury pool has. (b) The number of murders in a city next month, which averages 25 per month. (c) The number of houses a burglar tries before finding an unlocked one, if 10% of houses are unlocked. (d) The number of women on a 5-person panel chosen at random from 9 men and 6 women.

    Use the algorithm in Section 4.8: fixed trials or waiting? With or without replacement from a small group? Or just a rate?

    (a) Bin(12,0.3); jurors aren't independent draws if the pool is small (then hypergeometric). (b) Pois(25); murders can cluster (a single incident with several victims, retaliation), breaking independence. (c) Geom(0.1); a burglar doesn't choose houses at random, and unlocked houses may cluster on certain streets. (d) Hypergeometric with N=15, M=6, n=5; assumes the panel really is chosen at random.

  12. Regression to the mean. A school district names its 5 lowest-scoring schools (out of 100) as "failing" and gives them extra tutoring. Next year, their average score rises noticeably. (a) Give a reason this could happen even if the tutoring had no effect. (b) Design a better way to evaluate the tutoring.

    Test scores vary by chance from year to year. Why were these 5 schools chosen? Think about the hot-spots widget in Section 4.7.

    (a) The schools were chosen because their scores were unusually low. Part of a low score is bad luck (a difficult year, a few absent students), and next year's luck is likely to be closer to average, so their scores would tend to rise anyway: regression to the mean. (b) Among the low-scoring schools, randomly choose which ones get tutoring and compare the change in scores between tutored and untutored schools over the same year.

  13. How long should a quiz be? A teacher wants a true/false quiz on which a student who guesses every answer has less than a 5% chance of scoring 70% or more. Using quizzes of 10, 20 or 30 questions, which is the shortest that works?

    A guesser's score is Bin(n,0.5). "70% or more" of 10 questions is at least 7 right, so compute Pr(X≥7)=1−Pr(X≤6) = 1 - pbinom(6, 10, 0.5), and similarly for 20 (at least 14) and 30 (at least 21).

    10 questions: Pr(X≥7)≈0.172. 20 questions: Pr(X≥14)≈0.058, just too high. 30 questions: Pr(X≥21)≈0.021. So 30 questions. More questions make it harder to do well by luck, because the guesser's fraction correct concentrates around 0.5 (the Law of Large Numbers again).

  14. Are great discoveries Poisson? Using R's discoveries (Example 4.2), (a) compare the mean and variance of the yearly counts. (b) Compute the number of years out of 100 that a Poisson distribution with the same mean predicts for 0 to 6 discoveries, and compare with the data. (c) Suggest a reason for any mismatch.

    d <- as.numeric(discoveries); then mean(d), var(d) and round(100 * dpois(0:6, mean(d)), 1). Compare with table(d). Remember the Poisson's fingerprint.

    (a) Mean 3.1, variance 5.08: much bigger than the mean, so the counts are overdispersed. (b) Poisson predicts about 4.5, 14.0, 21.6, 22.4, 17.3, 10.7 and 5.6 years with 0 to 6 discoveries, against 9, 12, 26, 20, 12, 7 and 6 observed; it predicts too few years with 0 and with 7 or more (3.9 predicted, 8 observed). (c) The Poisson assumes a constant rate, but discoveries came in bursts (eras of rapid progress, and quieter periods such as wartime), so the rate itself varied from year to year. A varying rate makes counts more spread out than a single Poisson. The negative binomial is often used for such overdispersed counts.

  15. Settling in Catan. In the board game Settlers of Catan, two dice are rolled every turn, and a settlement collects one resource whenever the total matches the number on an adjacent tile. (a) A settlement touches tiles numbered 6, 8 and 9. What is the expected number of resources it collects per roll? (b) Over 60 rolls? (c) Compare a settlement on tiles 2, 3 and 12. Why do experienced players avoid it?

    Write the number collected per roll as a sum of three indicators, one per tile. Pr(total=6)=536; use the dice-total distribution from Example 3.22 for the others, then linearity.

    (a) 536+536+436=1436≈0.39 resources per roll. (b) 60×1436≈23.3. (c) 1+2+136=436≈0.11 per roll, about 6.7 in 60 rolls: less than a third as productive. (The game prints the "hot" numbers 6 and 8 in red for this reason.)