Probability and Statistics · Chapter 5

Chapter 5
Continuous random variables

Lectures 12–14 · measuring what happens: densities, the Gaussian curve, waiting times and the other shapes of chance

Cartoon: exactly six feetA tall stick figure stands next to a measuring stick and asks: What is the probability I am exactly six feet tall? A second figure with a magnifying glass replies: Zero. But you have to be some height, so... welcome to Chapter 5. Chance I'm exactly6 feet tall?Zero. Yet youare SOME height.
for measurements, single values have probability zero; intervals do not

Chapter 4 was about counting: how many passengers, how many fakes, how many calls. This chapter is about measuring: how tall, how long, how heavy, how concentrated. A person's height, the time until the next earthquake, the alcohol concentration in a blood sample, the age of a bone found at a crime scene. These quantities don't jump from one value to the next; they can take any value in an interval, and that changes the mathematics in a small but important way.

Here is the puzzle that drives the chapter. What is the probability that a randomly chosen man is exactly 70 inches tall? Not 70.1, not 69.99, but 70.000000... exactly. There are infinitely many possible heights, so the answer has to be zero. Yet every man has some height. How can every individual height have probability zero, when the probabilities must add up to 1? The answer is to stop asking about single values and start asking about intervals, and to measure probability as an area under a curve.

Here is the route through the chapter.

The calculus you need is in Section 0.4: areas under curves are integrals.

Densities serve the two goals of the course just as PMFs did. For prediction, a density fitted to past measurements tells us how often to expect future values in any range: how many sons will be over six feet, how long until the next mine disaster, how often an honest driver will be flagged by a breathalyser. For inference, we reverse the question: what does a measurement tell us about the hidden quantity behind it, such as a driver's true alcohol level, the age of a body, or a player's true shooting percentage? Along the way, watch for a third question that underlies both: has the mechanism that produced the data stayed the same? A model fitted to one era (the coal mines before 1890) can predict badly in another.

Think About It: Before You Start

A breathalyser reads 0.081 g/dL, just over the legal driving limit of 0.08. The device's readings are known to vary by a few thousandths around the true value. Should the driver be convicted? What would you need to know about the device to decide? Hold on to your answer: Example 5.7 works it out.

You'd want to know how big the measurement error typically is, and how likely a reading of 0.081 or more would be if the driver's true level were just below 0.08. If readings routinely vary by 0.005 either way, a reading of 0.081 is entirely consistent with a true level under the limit. Many jurisdictions deal with this by requiring two readings, or by subtracting a margin for error, and the size of that margin comes straight from the Gaussian distribution of measurement errors in Section 5.3.

Lecture 12 — Densities, expected value and the uniform

5.1 From histograms to densities

Galton's heights

In the 1880s the English scientist Francis Galton (a half-cousin of Charles Darwin) collected the heights of nearly 1,000 adult children and their parents, to study how height is inherited. His data still survive, and they're a good place to see how a continuous distribution behaves.

Example 5.1: Galton's Sons ★ lecture example

Galton's data include the heights, in inches, of 481 adult sons. (a) Draw a density histogram of their heights, with narrower and narrower bins. (b) What fraction were between 5 ft 7 in (67 inches) and 6 ft (72 inches)? (c) What does the histogram look like as the bins shrink?

The data are in the R package HistData as GaltonFamilies. To avoid installing anything, we read the same data straight from an online copy:

R
galton <- read.csv("https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/HistData/GaltonFamilies.csv")
sons <- galton$childHeight[galton$gender == "male"]
length(sons)
summary(sons)
mean(sons >= 67 & sons < 72)     # fraction between 67 and 72 inches
output
[1] 481
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  60.00   67.50   69.20   69.23   71.00   79.00 
[1] 0.6569647

(a) A density histogram (Section 2.1) scales each bar so its area is the fraction of sons in that bin. Here are three bin widths:

R
h <- rbind(data.frame(width = "2 inch bins", height = sons),
           data.frame(width = "1 inch bins", height = sons),
           data.frame(width = "half-inch bins", height = sons))
h$width <- factor(h$width, levels = c("2 inch bins", "1 inch bins", "half-inch bins"))
ggplot(h, aes(height)) +
  geom_histogram(data = subset(h, width == "2 inch bins"), aes(y = after_stat(density)), binwidth = 2, boundary = 0, colour = "white") +
  geom_histogram(data = subset(h, width == "1 inch bins"), aes(y = after_stat(density)), binwidth = 1, boundary = 0, colour = "white") +
  geom_histogram(data = subset(h, width == "half-inch bins"), aes(y = after_stat(density)), binwidth = 0.5, boundary = 0, colour = "white") +
  facet_wrap(~ width) +
  labs(x = "height of son (inches)", y = "density")
Three density histograms of the heights of 481 sons in Galton's data, with bin widths of…Three density histograms of the heights of 481 sons in Galton's data, with bin widths of 2 inches, 1 inch and half an inch. All three are single-peaked and roughly symmetric around 69 inches, ranging from about 60 to 79 inches. The narrower the bins, the more jagged the outline, but the overall bell shape stays the same. 2 inch bins 1 inch bins half-inch bins 60 65 70 75 80 60 65 70 75 80 60 65 70 75 80 0.00 0.05 0.10 0.15 0.20 height of son (inches) density

(b) About 65.7% of the sons were at least 67 and under 72 inches tall.

(c) Whatever the bin width, the outline has the same bell shape, peaking near 69 inches. With more and more data and narrower and narrower bins, the outline would settle down to a smooth curve. That curve is the density of the height distribution. The widget below does exactly this with simulated heights like Galton's: watch the bars smooth out into a curve, and watch the probability of a single bin shrink as the bin gets narrower.

A detail worth noticing. The half-inch histogram has spikes at whole inches. Heights were measured to the nearest quarter or half inch and many were written down as whole numbers, a common habit called heaping. That's why we asked about "at least 67 and under 72": an interval that cuts through a heap of recorded 72s would give a misleading answer. Measurement is never perfectly continuous.

Source: F. Galton (1886), "Regression towards mediocrity in hereditary stature", Journal of the Anthropological Institute 15, 246–263; data as transcribed by J. A. Hanley (2004), The American Statistician 58, 237–243.

From histogram to density curve

This is Example 5.1 in motion. We simulate adult men's heights (in inches) like the sons in Galton's data: mean 69.2, standard deviation 2.6. With few people and wide bins, the density histogram is blocky. Add more people and shrink the bins: the outline smooths into a curve. The probability of a bin is its area (height × width), so the probability of one exact height shrinks to zero as the bins shrink, even though the curve's height does not.

Density histogram of simulated heights with adjustable bin width and number of people…Density histogram of simulated heights with adjustable bin width and number of people, with the smooth Gaussian density drawn on top.

Probability density functions

The histogram shows the key idea. For a measurement, the probability of an interval is the area of the histogram over that interval. In the limit, the probability that X falls between a and b is the area under the density curve from a to b.

Definition: Continuous Random Variable and Density

A random variable X is continuous if there is a function f(x), called its probability density function (PDF, or just density), such that for all a≤b, Pr(a≤X≤b)=∫abf(x)dx. Every density satisfies

  1. f(x)≥0 for all x, and
  2. ∫−∞∞f(x)dx=1: the total area is 1.

Three consequences follow straight away, and each is a common source of confusion.

Example 5.2: Where Does the Dart Land? ★ lecture example

A dart lands at a uniformly random point on a round board of radius 1 (say, 1 foot). Let R be its distance from the centre. (a) Show that Pr(R≤r)=r2 for 0≤r≤1. (b) Find the density of R and check that it's a valid density. (c) Find the probability that the dart lands within half a foot of the centre, and the probability it lands between 0.5 and 0.6 feet out.

(a) Probability is area. "Uniformly random point" means the probability of landing in any region is that region's share of the board's area. The dart lands within r of the centre exactly when it lands in the circle of radius r, so Pr(R≤r)=area of circle of radius rarea of the board=πr2π⋅12=r2.

(b) The density is the rate at which this probability grows, its derivative: f(r)=ddrr2=2r,0≤r≤1, and f(r)=0 outside [0,1]. It's never negative, and its total area is ∫012rdr=[r2]01=1. Valid.

(c) Within half a foot: Pr(R≤0.5)=0.52=0.25. Between 0.5 and 0.6: Pr(0.5≤R≤0.6)=∫0.50.62rdr=0.62−0.52=0.36−0.25=0.11.

The surprise. Only a quarter of random darts land within half the radius of the centre. The density 2r rises towards the edge, because there is more board far out: a thin ring at distance r has circumference 2πr, so outer rings hold more area. Throw some darts:

R
set.seed(5)
x <- runif(100000, -1, 1); y <- runif(100000, -1, 1)
inside <- x^2 + y^2 <= 1                   # keep points that hit the board
R <- sqrt(x[inside]^2 + y[inside]^2)
mean(R <= 0.5)                             # close to 0.25
mean(R >= 0.5 & R <= 0.6)                  # close to 0.11
output
[1] 0.2482223
[1] 0.1093537

Picture. The density f(r)=2r, with the two probabilities in (c) as areas:

R
r <- seq(0, 1, by = 0.005)
d <- data.frame(r, f = 2 * r)
ggplot(d, aes(r, f)) +
  geom_area(data = subset(d, r <= 0.5), fill = "steelblue", alpha = 0.4) +
  geom_area(data = subset(d, r >= 0.5 & r <= 0.6), fill = "orange", alpha = 0.7) +
  geom_line(linewidth = 1) +
  annotate("text", x = 0.36, y = 0.2, label = "0.25") +
  annotate("text", x = 0.55, y = 1.35, label = "0.11") +
  labs(x = "distance from centre, r (feet)", y = "density f(r)")
Plot of the dart-distance density f(r) = 2r, a straight line rising from 0 at r = 0 to 2…Plot of the dart-distance density f(r) = 2r, a straight line rising from 0 at r = 0 to 2 at r = 1. The triangle under the line from 0 to 0.5 is shaded light blue, area 0.25. The strip from 0.5 to 0.6 is shaded orange, area 0.11. 0.25 0.11 0.0 0.5 1.0 1.5 2.0 0.00 0.25 0.50 0.75 1.00 distance from centre, r (feet) density f(r)

Throwing darts: probability is area

Each dart lands at a uniformly random point on a round board of radius 1. Let R be its distance from the centre. Throw darts and watch the density histogram of R (right) take the shape of the density curve f(r) = 2r. Drag the slider to choose a distance a: the readout compares the fraction of darts landing within a of the centre with the area under the curve from 0 to a.

A round dart board with the darts thrown so far, and a shaded inner circle of radius aA round dart board with the darts thrown so far, and a shaded inner circle of radius a. Density histogram of the distances from the centre, with the density curve 2r and the…Density histogram of the distances from the centre, with the density curve 2r and the area from 0 to a shaded.

The CDF, again

The cumulative distribution function F(x)=Pr(X≤x) is defined exactly as in Chapter 4. For a continuous random variable it is the area under the density to the left of x: F(x)=∫−∞xf(t)dt. By the Fundamental Theorem of Calculus, the density is the derivative of the CDF, f(x)=F′(x), which is how we got 2r from r2 in Example 5.2. Instead of a staircase, the CDF of a continuous random variable is a smooth curve rising from 0 to 1, and it is steepest where the density is highest.

The CDF is the area so far

Slide x from left to right. The shaded area under the density (top) is Pr(X ≤ x). The same number is the height of the CDF (bottom). Where the density is tall, the area grows fast and the CDF is steep; where the density is near zero, the CDF is flat.

TopTop: a two-humped density with the area to the left of x shaded. Bottom: the matching cumulative distribution function with a point at height equal to the shaded area.

The CDF also gives quantiles. The p-quantile of a continuous random variable is the value q with F(q)=p: a fraction p of the probability lies to its left. The median is the 0.5-quantile.

Example 5.3: The Median Dart ★ lecture example

For the dart in Example 5.2, find the median distance from the centre and the 90th percentile.

Solve F(q)=p with F(r)=r2: q2=p, so q=p.

  • Median: q=0.5≈0.707 feet. Half of all darts land more than 0.7 feet from the centre of a 1-foot board.
  • 90th percentile: q=0.9≈0.949 feet. One dart in ten lands in the outermost 5% of the radius.

So a "typical" random dart is much nearer the rim than the centre, which is why darts players aim, and why a random scatter of shots on a target looks emptier in the middle than you'd expect.

Check Yourself

A continuous random variable has density f. Which statement is always true?

For what value of c is f(x)=cx2 on 0≤x≤1 (and 0 elsewhere) a valid density?

With that density, f(x)=3x2 on [0,1], find Pr(X≤12).

Think About It: How Precise Is a Measurement?

A forensic report says a footprint is "28.0 cm long". The probability that a true length is exactly 28.0 cm is zero, so what does this report actually tell a jury? How would you rewrite it to be honest about uncertainty?

It really means the length lies in an interval: perhaps 27.95 to 28.05 cm if it was rounded to the nearest millimetre, or wider still once the ruler's error and the stretch of the impression are counted. An honest report gives the interval or a measurement uncertainty: "28.0 cm ± 0.3 cm (95%)", say. This is exactly the shift this section makes: continuous quantities are described by probabilities of intervals, not of single values. Chapter 8 shows how to compute such intervals.

Key Takeaways

  • A continuous random variable has a density f(x)≥0 with total area 1; probabilities are areas: Pr(a≤X≤b)=∫abf(x)dx.
  • Single values have probability zero, so ≤ and < don't matter. A density is probability per unit, and can exceed 1.
  • F(x)=∫−∞xf(t)dt and f=F′. The p-quantile solves F(q)=p.

5.2 Expected value, variance and the uniform distribution

Every idea from Chapter 4 carries over, with sums replaced by integrals and the PMF replaced by the density.

Definition: Expected Value and Variance of a Continuous Random Variable

If X has density f, its expected value and variance are E[X]=∫−∞∞xf(x)dx,Var[X]=∫−∞∞(x−μ)2f(x)dx, where μ=E[X] (provided the integral of |x|f(x) is finite). More generally, E[g(X)]=∫g(x)f(x)dx.

All the rules carry over unchanged, with the same proofs (sums become integrals): linearity E[aX+b]=aE[X]+b; the shortcut Var[X]=E[X2]−(E[X])2; and Var[aX+b]=a2Var[X]. The interpretations do too: E[X] is the long-run average and the balance point of the density, and the standard deviation is a typical distance from the mean.

Example 5.4: The Average Dart ★ lecture example

For the dart distance R with density f(r)=2r on [0,1], find E[R], Var[R] and SD[R]. Compare the mean with the median from Example 5.3.

Mean. E[R]=∫01r⋅2rdr=∫012r2dr=[2r33]01=23≈0.667.

Variance, by the shortcut formula. First E[R2]=∫01r2⋅2rdr=∫012r3dr=[r42]01=12, so Var[R]=12−(23)2=12−49=118,SD[R]=1/18≈0.236.

Mean vs median. The mean, 0.667, is below the median, 0.707. The density rises to the right and stops abruptly at 1, so its long tail is on the left: it's left-skewed, and (as for data in Chapter 2) the mean is pulled towards the long tail. R can check the integrals numerically:

R
integrate(function(r) r * 2 * r, lower = 0, upper = 1)      # E[R]
integrate(function(r) r^2 * 2 * r, lower = 0, upper = 1)    # E[R^2]
output
0.6666667 with absolute error < 7.4e-15
0.5 with absolute error < 5.6e-15
R
ggplot(data.frame(r = seq(0, 1, by = 0.005)), aes(r, 2 * r)) +
  geom_line(linewidth = 1) +
  geom_vline(xintercept = 2/3) +
  geom_vline(xintercept = sqrt(0.5), linetype = "dashed") +
  annotate("text", x = 2/3 - 0.02, y = 1.9, label = "mean", hjust = 1) +
  annotate("text", x = sqrt(0.5) + 0.02, y = 1.9, label = "median", hjust = 0) +
  labs(x = "distance from centre, r (feet)", y = "density f(r)")
The dart density f(r) = 2r on 0 to 1, with a solid vertical line at the mean 0.667 and a…The dart density f(r) = 2r on 0 to 1, with a solid vertical line at the mean 0.667 and a dashed vertical line at the median 0.707. The mean is to the left of the median. mean median 0.0 0.5 1.0 1.5 2.0 0.00 0.25 0.50 0.75 1.00 distance from centre, r (feet) density f(r)

The uniform distribution

The simplest continuous distribution spreads probability evenly over an interval.

Definition: Uniform Distribution

X has the uniform distribution on [a,b], written X∼Unif(a,b), if its density is constant on that interval: f(x)=1b−a,a≤x≤b, and 0 elsewhere. Then E[X]=a+b2 and Var[X]=(b−a)212.

The total area is a rectangle of width b−a and height 1b−a, which is 1. For the mean, ∫abxb−adx=b2−a22(b−a)=a+b2, the midpoint, as symmetry suggests. For the variance, E[X2]=∫abx2b−adx=b3−a33(b−a)=a2+ab+b23, and subtracting (a+b2)2 leaves (b−a)212 after a little algebra. ◼∎

For a uniform distribution, probabilities are just lengths: Pr(c≤X≤d)=d−cb−a for any [c,d] inside [a,b].

Example 5.5: Waiting for the Bus ★ lecture example

A bus comes every 12 minutes, like clockwork, and you arrive at the stop at a random time without checking the timetable. Let W be your wait. (a) What is the distribution of W? (b) What is your expected wait, and its standard deviation? (c) What is the probability you wait more than 10 minutes?

(a) Arriving "at a random time" makes every point in the 12-minute cycle equally likely, so W∼Unif(0,12), with density 112 on [0,12].

(b) E[W]=0+122=6 minutes, and SD[W]=12212=12≈3.46 minutes.

(c) Pr(W>10)=12−1012=16: the length of the interval [10,12], divided by 12.

R
1 - punif(10, min = 0, max = 12)
output
[1] 0.1666667

Critical thinking. Real buses aren't like clockwork: they bunch up, and gaps vary. Surprisingly, irregular buses make your expected wait longer than half the average gap, because you're more likely to arrive during a long gap than a short one (long gaps take up more of the timeline). This is called the inspection paradox, and it's why waits always feel longer than the timetable suggests.

R
ggplot() +
  annotate("rect", xmin = 10, xmax = 12, ymin = 0, ymax = 1/12, fill = "orange", alpha = 0.7) +
  annotate("segment", x = 0, xend = 12, y = 1/12, yend = 1/12, linewidth = 1) +
  geom_vline(xintercept = 6, linetype = "dashed") +
  scale_y_continuous(limits = c(0, 0.12)) +
  labs(x = "wait W (minutes)", y = "density")
The uniform density of the wait for a busThe uniform density of the wait for a bus: a flat line at height 1/12 from 0 to 12 minutes. The rectangle from 10 to 12 minutes is shaded orange, one sixth of the total area. A dashed line marks the mean wait of 6 minutes. 0.000 0.025 0.050 0.075 0.100 0.125 0.0 2.5 5.0 7.5 10.0 12.5 wait W (minutes) density

Explore the uniform distribution

Move the sliders to change the parameters. Press draw a random sample to simulate values from this distribution: their density histogram (orange) appears beneath the curve, and with a large sample it hugs the curve. Tick shade and move x to see Pr(X ≤ x) as an area, with the R command that computes it.

Density curve for the chosen parametersDensity curve for the chosen parameters. A random sample can be drawn and shown as a density histogram beneath the curve, and the area to the left of x can be shaded.

Simulation: turning uniform numbers into anything

Computers generate random numbers that are uniform on [0,1]; runif() in R. How does R produce Gaussian or exponential random numbers from them? The trick uses quantiles: if U∼Unif(0,1) and F is a continuous CDF, then X=F−1(U), the U-quantile, has CDF F.

For any x, X≤x exactly when F−1(U)≤x, that is, when U≤F(x) (since F is increasing). And Pr(U≤F(x))=F(x) because U is uniform. ◼∎

For the dart, F(r)=r2, so R=U simulates dart distances without throwing any darts. This is the inverse transform method.

Turning random numbers into any distribution

A computer's basic random numbers are uniform between 0 and 1. To get a draw from another distribution, pick a uniform number u on the vertical axis, go across to the CDF, and drop down to the horizontal axis: the x you land on is the u-quantile. Press draw to do this many times; the histogram of the results takes the shape of the target density, because steep parts of the CDF catch many u's.

TopTop: the CDF with the latest uniform draw traced across and down. Bottom: histogram of all the values produced, with the target density.

Think About It: The Inspection Paradox in the Wild

A university reports that its average class size is 30. A student survey finds that the average student is in a class of 60. Both are correct (Chapter 2's "pooling in your own life" box raised the same puzzle; now we can put numbers on it). How? Which number would you use to predict the size of a class a randomly chosen student walks into, and which to plan the number of classrooms?

Big classes contain many students, so when you sample students, you hit big classes more often, just as a random arrival at a bus stop is more likely to fall in a long gap. If there are nine classes of 20 and one of 120, the average class has 300/10=30 students, but 120 of the 300 students are in the big class, so the average student's class has (180×20+120×120)/300=60 students. To predict a random student's experience, use the student-weighted average; to plan rooms, the class average. Both are predictions; they just predict different things. Before using any average, ask: averaged over what?

Key Takeaways

  • E[X]=∫xf(x)dx and Var[X]=E[X2]−μ2: the same rules as Chapter 4, with integrals.
  • Uniform Unif(a,b): flat density; mean a+b2, variance (b−a)212; probabilities are lengths.
  • If U is uniform, F−1(U) has CDF F: that's how computers simulate any distribution.

Lecture 13 — The Gaussian distribution

5.3 The Gaussian distribution

The bell curve

Galton's sons' heights, measurement errors in Michelson's speed of light, birth weights, exam scores: an astonishing number of measurements have the same symmetric, bell-shaped distribution. It has a formula, and it is the most important distribution in statistics.

Definition: Gaussian Distribution

X has the Gaussian distribution with mean μ and standard deviation σ>0, written X∼N(μ,σ2), if its density is f(x)=1σ2πexp(−(x−μ)22σ2),−∞<x<∞. Then E[X]=μ and Var[X]=σ2. The standard Gaussian distribution is N(0,1), and a standard Gaussian random variable is usually called Z.

(The notation follows the convention that the second number is the variance σ2. R's functions take the standard deviation instead: pnorm(x, mean, sd). Always check which one a formula or program wants.)

History: Why Gaussian and Not Normal?

Most textbooks, and R, call this distribution the normal distribution. We keep the standard notation N(μ,σ2), and R's functions dnorm, pnorm, qnorm and rnorm, where the "norm" stands for normal.

The word normal was applied to the curve by several scientists in the 1870s and 1880s, including Francis Galton, and Karl Pearson made it standard in the 1890s. It carried a message. In the 1830s and 1840s the Belgian astronomer Adolphe Quetelet had argued that the average of a human trait described an ideal "average man" (l'homme moyen), and that variation around it was like error in a measurement: nature missing its target. Galton used the bell curve to rank people into grades of "natural ability", and the language of a normal middle and abnormal tails fitted the eugenic project of sorting people into the fit and the unfit (the history box after Example 5.6 tells that story). Pearson himself came to regret the name. In 1920 he wrote:

"Many years ago I called the Laplace–Gaussian curve the normal curve, which name, while it avoids an international question of priority, has the disadvantage of leading people to believe that all other distributions of frequency are in one sense or another 'abnormal'."

The name Gaussian is already standard in physics, engineering and machine learning, and it describes the curve without judging anyone. It isn't a perfect name either. Abraham de Moivre found the curve in 1733, and Pierre-Simon Laplace developed its theory alongside Gauss. This is an example of what the statistician Stephen Stigler called his "law of eponymy": no scientific discovery is named after its original discoverer. But it is a neutral name, and it carries a useful reminder: most data are not Gaussian, and that isn't a defect.

When you read other books and papers, translate:

these notes other books
Gaussian normal
standard Gaussian standard normal
Gaussian Q-Q plot normal Q-Q plot
log-Gaussian lognormal

How to read the formula: the curve is highest at x=μ, where the exponent is zero. As x moves away from μ, the exponent becomes more and more negative quadratically, so the density falls off very fast: values more than 3 standard deviations from the mean are rare, and beyond 5 they are almost unheard of. The factor 1σ2π in front makes the total area 1 (a famous integral, proved in the exercises of Chapter 6), and the σ inside sets the width.

Explore the Gaussian distribution

Move the sliders to change the parameters. Press draw a random sample to simulate values from this distribution: their density histogram (orange) appears beneath the curve, and with a large sample it hugs the curve. Tick shade and move x to see Pr(X ≤ x) as an area, with the R command that computes it.

Density curve for the chosen parametersDensity curve for the chosen parameters. A random sample can be drawn and shown as a density histogram beneath the curve, and the area to the left of x can be shaded.

Standardizing

There is no formula for the area under a Gaussian curve; it has to be computed numerically. Fortunately, every Gaussian distribution is a stretched and shifted copy of the standard Gaussian, so one table (or one R function) covers them all.

Theorem: Standardizing a Gaussian Random Variable

If X∼N(μ,σ2), then Z=X−μσ∼N(0,1). Consequently Pr(X≤x)=Pr(Z≤x−μσ)=Φ(x−μσ), where Φ (capital phi) is the CDF of the standard Gaussian.

For any z, Pr(Z≤z)=Pr(X≤μ+σz)=∫−∞μ+σzf(x)dx, where f is the N(μ,σ2) density above. Substitute t=(x−μ)/σ, so dx=σdt and the upper limit becomes z: Pr(Z≤z)=∫−∞z12πe−t2/2dt, which is the standard Gaussian CDF. ◼∎

The quantity x−μσ is a z-score, just as for data in Chapter 2: the number of standard deviations x lies from the mean. Standardizing turns every Gaussian question into a question about Z.

Standardizing keeps the area

Choose a Gaussian distribution N(μ, σ²) and an interval from a to b. The top panel shades Pr(a ≤ X ≤ b). The bottom panel shows the same region after standardizing: subtract μ and divide by σ, turning a and b into their z-scores. The two shaded areas are always equal.

TopTop: a Gaussian density with the area between a and b shaded. Bottom: the standard Gaussian with the area between the two z-scores shaded.

Idea: The 68–95–99.7 Rule

For any Gaussian distribution, the probability of falling within 1, 2 and 3 standard deviations of the mean is about 68%, 95% and 99.7%: Pr(|Z|≤1)≈0.683,Pr(|Z|≤2)≈0.954,Pr(|Z|≤3)≈0.997. This is where Chapter 2's rule of thumb comes from. The precise value for 95% is ±1.96 standard deviations, a number you'll meet again in Chapter 8.

R
z <- seq(-4, 4, by = 0.01); d <- data.frame(z, f = dnorm(z))
ggplot(d, aes(z, f)) +
  geom_area(data = subset(d, abs(z) <= 3), fill = "steelblue", alpha = 0.15) +
  geom_area(data = subset(d, abs(z) <= 2), fill = "steelblue", alpha = 0.25) +
  geom_area(data = subset(d, abs(z) <= 1), fill = "steelblue", alpha = 0.4) +
  geom_line(linewidth = 1) +
  annotate("text", x = 0, y = 0.17, label = "68.3%") +
  annotate("text", x = 2.45, y = 0.09, label = "95.4%", size = 3.8) +
  annotate("text", x = 3.35, y = 0.04, label = "99.7%", size = 3.8) +
  scale_x_continuous(breaks = -3:3, labels = c("μ−3σ", "μ−2σ", "μ−σ", "μ", "μ+σ", "μ+2σ", "μ+3σ")) +
  labs(x = NULL, y = "density")
The standard Gaussian density curve from minus 4 to 4, with three nested shaded bandsThe standard Gaussian density curve from minus 4 to 4, with three nested shaded bands: the darkest from minus 1 to 1 (68.3% of the area), a lighter band out to plus and minus 2 (95.4%), and the lightest out to plus and minus 3 (99.7%). Labels give the three percentages. 68.3% 95.4% 99.7% 0.0 0.1 0.2 0.3 0.4 μ−3σ μ−2σ μ−σ μ μ+σ μ+2σ μ+3σ density

In R, pnorm(x, mean, sd) gives Pr(X≤x) and qnorm(p, mean, sd) gives the p-quantile.

Example 5.6: How Tall Were Galton's Sons? ★ lecture example

Galton's 481 sons had mean height 69.2 inches and standard deviation 2.6 inches. Model their heights as N(69.2,2.62). (a) What fraction does the model predict between 67 and 72 inches? Compare with the data (Example 5.1). (b) What fraction were 6 ft 2 in (74 inches) or taller? (c) How tall must a son be to be in the tallest 5%? (d) Is the Gaussian model reasonable?

(a) Standardize both ends: z1=67−69.22.6≈−0.85,z2=72−69.22.6≈1.08, so Pr(67≤X≤72)=Φ(1.08)−Φ(−0.85)≈0.860−0.198=0.662. The data gave 0.657. Very close. (With the unrounded mean and SD, as in the R code below, the model gives 0.657 too.)

(b) z=74−69.22.6≈1.85, so Pr(X≥74)=1−Φ(1.85)≈0.032. In the data, 16 of 481 sons (3.3%) were at least 74 inches.

(c) We need the 95th percentile. The standard Gaussian's is z=1.645 (qnorm(0.95)), so x=μ+zσ=69.2+1.645×2.6≈73.5 inches.

R
mu <- mean(sons); sigma <- sd(sons)
c(mu, sigma)
pnorm(72, mu, sigma) - pnorm(67, mu, sigma)      # (a) model
mean(sons >= 74); 1 - pnorm(74, mu, sigma)       # (b) data and model
qnorm(0.95, mu, sigma); quantile(sons, 0.95)     # (c) model and data
output
[1] 69.234096  2.623905
[1] 0.6568228
[1] 0.03326403
[1] 0.03465909
[1] 73.55004
95% 
 73 

(d) The model's answers match the data closely, and a picture shows why:

R
ggplot(data.frame(sons), aes(sons)) +
  geom_histogram(aes(y = after_stat(density)), binwidth = 1, boundary = 0, colour = "white") +
  stat_function(fun = dnorm, args = list(mean = mu, sd = sigma), linewidth = 1) +
  labs(x = "height of son (inches)", y = "density")
Density histogram of the heights of Galton's 481 sons with 1-inch bins, with a Gaussian…Density histogram of the heights of Galton's 481 sons with 1-inch bins, with a Gaussian density curve with mean 69.2 and standard deviation 2.6 drawn on top. The curve follows the outline of the histogram closely, peaking near 69 inches. 0.00 0.05 0.10 0.15 60 65 70 75 height of son (inches) density

A Gaussian Q-Q plot (Section 2.5), qqnorm(sons); qqline(sons), is nearly straight. The model describes the sons well. It would not describe all 934 children together, because sons and daughters are two groups with different means; mixing them gives a flatter, wider distribution than either.

Prediction and inference. The model was inferred from data (the mean and SD estimate the population's), and then used to predict fractions. Those predictions are checkable, and checking them against the data is how we decided the model was trustworthy. Its predictions far out in the tails, where there is little data to check against, deserve less trust.

History: Galton's Heights, and Why He Collected Them

The heights in this chapter come from a remarkable dataset. In 1884 Francis Galton (1822–1911), a half-cousin of Charles Darwin, collected the heights of the parents and adult children of 205 families, partly by offering cash prizes for detailed family records. From these data he found that tall parents tend to have tall children, but less extremely tall than themselves. He published this in 1886 as "Regression towards mediocrity in hereditary stature", and it is the origin of the words regression and regression to the mean (Section 4.7). Two years later he introduced correlation (Chapter 6). Every regression model fitted today, in medicine, economics or machine learning, descends from this work.

Galton collected the data for a reason. In 1883 he coined the word eugenics for a programme to improve the human population by encouraging people he considered "fit" to have more children and discouraging the "unfit". In Hereditary Genius (1869) he had ranked whole races by their supposed natural ability. Others turned the idea into policy:

  • more than 30 American states passed compulsory sterilization laws; the US Supreme Court upheld Virginia's law in Buck v. Bell (1927), and more than 60,000 people were sterilized under such laws;
  • eugenic arguments helped shape the US Immigration Act of 1924, which restricted immigration from southern and eastern Europe and barred it from Asia;
  • Nazi Germany's sterilization law of 1933 drew on American models.

In 2020 University College London, where Galton had endowed the chair of eugenics, removed his name and Pearson's from its buildings.

None of this followed from the mathematics. Regression and correlation measure how quantities vary together; they cannot say why. Galton read the similarity of parents and children as evidence that ability and character are mainly inherited. But families also share wealth, food, schooling and opportunity, which are confounders in the language of Chapter 1's DAGs, and his data could not separate these causes. The tools were sound; the inference was not.

The words carry the history too. "Regression" originally meant a drift back towards "mediocrity". That is one reason Aubrey Clayton, in Bernoulli's Fallacy (2021), proposes calling linear regression simply linear modelling, and avoiding "correlation" altogether. These notes keep the standard words, which you will need in order to read the scientific literature. But knowing their origin is part of being statistically literate. The same calculation can inform or mislead, and only a reader who understands where the numbers came from can tell which.

Causal Inference: Why Are So Many Things Gaussian?

Why should heights follow a bell curve? Think about what causes a person's height: hundreds of genes, each nudging height up or down a little, plus nutrition, childhood illnesses, sleep, and much else. Height is roughly the sum of many small, independent influences. The Central Limit Theorem of Chapter 7 says that such sums are approximately Gaussian, whatever the distributions of the individual pieces. That's the deep reason the bell curve is everywhere: measurement errors, test scores and birth weights are all sums of many small effects.

The same reasoning tells you when to expect a Gaussian distribution to fail. If one cause is large and dominant, the distribution follows that cause instead: adult heights for men and women together are a mixture of two bells, because sex has a big effect on height. Incomes, house prices and pollutant concentrations are shaped by causes that multiply rather than add, and are right-skewed (Section 5.6). Before assuming a Gaussian model, ask what produced the data: a DAG with many small arrows into the outcome suggests a bell; one big arrow suggests something else.

Example 5.7: Just Over the Limit? ★ lecture example

A breathalyser's readings follow a Gaussian distribution around the true blood alcohol concentration (BAC), with standard deviation 0.005 g/dL. A driver's true BAC is 0.075, below the legal limit of 0.08. (a) What is the probability that a single reading is 0.08 or above? (b) The policy is to take two independent readings and use the lower. What is the probability that both are 0.08 or above?

(a) The reading X∼N(0.075,0.0052). Standardize: Pr(X≥0.08)=Pr(Z≥0.08−0.0750.005)=Pr(Z≥1)=1−Φ(1)≈0.159. About one in six readings would put this driver over the limit, though their true level is under it.

(b) Both readings must be at least 0.08. They are independent, so multiply (Section 3.5): Pr(both≥0.08)=0.1592≈0.025.

R
1 - pnorm(0.08, mean = 0.075, sd = 0.005)        # (a)
(1 - pnorm(0.08, mean = 0.075, sd = 0.005))^2    # (b)
output
[1] 0.1586553
[1] 0.02517149
R
x <- seq(0.055, 0.095, by = 0.0001)
d <- data.frame(x, f = dnorm(x, 0.075, 0.005))
ggplot(d, aes(x, f)) +
  geom_area(data = subset(d, x >= 0.08), fill = "orange", alpha = 0.6) +
  geom_line() +
  geom_vline(xintercept = 0.08, linetype = "dashed") +
  labs(x = "breathalyser reading (g/dL)", y = "density")
Gaussian density curve of breathalyser readings centred at a true level of 0.075 with…Gaussian density curve of breathalyser readings centred at a true level of 0.075 with standard deviation 0.005. The area to the right of the legal limit 0.08, marked by a dashed line, is shaded orange: about 16% of the total area. 0 20 40 60 80 0.06 0.07 0.08 0.09 breathalyser reading (g/dL) density

What it means. Measurement error matters most for people near a threshold. A single reading would wrongly put a driver at 0.075 over the limit 16% of the time; requiring two readings cuts that to 2.5%. (The real situation is more complicated: the two readings aren't quite independent, because the same person and device produce both. Positive dependence would make the 2.5% an underestimate.) This is the kind of calculation forensic toxicologists use to set the "measurement uncertainty" they report alongside a result.

Turning it round. This example predicted readings from a known true level. A court faces the inference problem: given a reading of 0.081, what was the true level? Because readings scatter by 0.005, a true level anywhere from about 0.071 to 0.091 could easily produce it. Chapter 8 makes this precise with a confidence interval; a Bayesian would also use what is known about how common different BAC levels are among drivers who are tested.

The Gaussian approximation to the binomial

The binomial histograms in Chapter 4 looked more and more bell-shaped as n grew. That's not a coincidence: a binomial count is a sum of n independent indicators, so the Central Limit Theorem applies. For large n, Bin(n,p) is close to a Gaussian with the same mean np and variance np(1−p). Because the binomial is discrete, we treat each integer k as the interval [k−12,k+12]: this continuity correction noticeably improves the approximation.

Gaussian approximation to the binomial, with the continuity correction

Bars show Bin(n, p); the curve is the Gaussian with the same mean and variance. The shaded bars are Pr(X ≤ x). The Gaussian approximation with continuity correction uses the area under the curve up to x + 0.5, the right-hand edge of the last bar. Watch how the approximation improves as np and n(1 − p) grow.

Binomial bars with an overlaid Gaussian density curveBinomial bars with an overlaid Gaussian density curve; the bars up to x and the area under the curve up to x plus one half are shaded.

Example 5.8: The Airline, One Last Time

The airline sells 110 tickets, each holder showing up with probability 0.9. Use the Gaussian approximation, with the continuity correction, to estimate the probability that more than 100 passengers show up, and compare with the exact binomial answer of 0.329 from Example 4.11.

X∼Bin(110,0.9) has μ=110×0.9=99 and σ=110×0.9×0.1=9.9≈3.146. "More than 100" means X≥101, which the continuity correction treats as "above 100.5": Pr(X≥101)≈Pr(Z≥100.5−993.146)=Pr(Z≥0.477)≈0.317.

R
1 - pnorm(100.5, mean = 99, sd = sqrt(9.9))      # Gaussian approximation
1 - pbinom(100, 110, 0.9)                        # exact
output
[1] 0.3167767
[1] 0.3289856

The approximation gives 0.317 against the exact 0.329: close, though not perfect, because with p=0.9 the binomial is slightly skewed. With a computer we'd just use the exact answer; the approximation earns its keep in Chapters 7 to 9, where it lets us reason about averages and proportions without knowing their exact distribution.

Picture. The Gaussian curve (with the same mean and SD) over the binomial bars; the bars for 101 or more passengers, and the area beyond 100.5, are what we compared:

R
k <- 88:110
d <- data.frame(k, p = dbinom(k, 110, 0.9), over = k >= 101)
ggplot(d, aes(k, p, fill = over)) + geom_col(width = 0.8) +
  stat_function(fun = dnorm, args = list(mean = 99, sd = sqrt(9.9)), inherit.aes = FALSE, linewidth = 1) +
  scale_fill_manual(values = c("grey60", "orange"), guide = "none") +
  labs(x = "passengers who show up", y = "probability")
Bar chart of the binomial distribution with 110 trials and probability 0.9, for 88 to 110…Bar chart of the binomial distribution with 110 trials and probability 0.9, for 88 to 110 show-ups, with a Gaussian density curve of mean 99 and SD 3.15 drawn on top. The bars for 101 and above are orange; the curve follows the bars closely, a little to the left of them on the right-hand side. 0.00 0.05 0.10 90 95 100 105 110 passengers who show up probability

History: Ceres, Gauss and the Birth of the Bell Curve

On 1 January 1801, the Italian astronomer Giuseppe Piazzi discovered a new object in the night sky: Ceres, now known as a dwarf planet. He tracked it for about six weeks, and then it disappeared into the glare of the Sun. Astronomers had only a few, slightly inaccurate measurements, and no idea where it would reappear.

A 24-year-old German mathematician, Carl Friedrich Gauss, took on the problem. Using new methods, including what became the method of least squares, he found the orbit that best fitted the inaccurate observations. In December 1801 astronomers pointed their telescopes where Gauss said Ceres would be, and there it was.

In 1809 Gauss explained why least squares works. He assumed that the average of repeated measurements is the most probable value of the true quantity, showed that this forces measurement errors to follow a particular symmetric, bell-shaped curve, and showed that least squares then gives the most probable orbit (Chapter 8's maximum likelihood). That is why the curve carries his name, though Abraham de Moivre had already found it in 1733, as an approximation to the binomial.

The bell curve began as a model of errors in measuring the sky. Applying it to people came later, with Quetelet, who measured the chests of Scottish soldiers, and then Galton. Both moves are described in the history boxes earlier in this section.

Check Yourself

Find Pr(Z>2) for a standard Gaussian Z. (Use R: 1 - pnorm(2).)

Galton's daughters' heights are roughly N(64.1,2.42) inches. How tall would a daughter need to be to be taller than 99.99% of daughters? Give your answer to one decimal place.

Test scores are N(500,1002). Which is more unusual: a score of 720, or a score of 290?

Think About It: Abnormal, or Just Unlucky?

A lab uses a "reference range" for a blood marker: the middle 95% of healthy adults, mean ± 2 SD. If a healthy patient has 20 independent tests, each with its own 95% range, what's the chance at least one result is flagged as abnormal? What does this mean for interpreting a single flagged result?

Each healthy result is outside its range with probability 0.05, so Pr(at least one flag)=1−0.9520≈0.64. Most perfectly healthy people having a 20-test panel will have something flagged. A single flag is weak evidence on its own: it's the prediction "95% of healthy people fall here" applied twenty times, so some misses are expected. This is the multiple-testing problem again (Paul the octopus, cancer clusters), and Chapter 9 returns to it. Doctors interpret a flag alongside symptoms and repeat tests, which is Bayes' theorem in practice.

Key Takeaways

  • Gaussian N(μ,σ2): symmetric bell, mean μ, SD σ. About 68%, 95% and 99.7% lies within 1, 2 and 3 SD.
  • Standardize: Z=(X−μ)/σ∼N(0,1). In R: pnorm for probabilities, qnorm for quantiles.
  • Sums of many small independent effects are approximately Gaussian (the Central Limit Theorem). One dominant cause, or multiplying causes, break the bell.
  • Bin(n,p)≈N(np,np(1−p)) for large n; use the continuity correction.

Lecture 14 — Exponential, gamma, beta and other shapes

5.4 Waiting times: exponential and gamma

The exponential distribution

In Chapter 4, the Poisson distribution counted rare events (calls, accidents, decays) in a window of time. Now ask a different question about the same events: how long until the next one? The answer is a continuous random variable, and if events occur independently at a constant rate λ, its distribution is exponential.

Definition: Exponential Distribution

X has the exponential distribution with rate λ>0, written X∼Exp(λ), if its density is f(x)=λe−λx,x≥0, and 0 for x<0. Its CDF is F(x)=1−e−λx, so Pr(X>x)=e−λx, and E[X]=1λ,Var[X]=1λ2,median=ln2λ.

You've already met this density: Example 0.4 showed its total area is 1 and Example 0.5 computed its mean, 1/λ. The CDF comes from integrating: ∫0xλe−λtdt=1−e−λx. Setting F(m)=12 gives the median m=ln2/λ≈0.69/λ, below the mean: the exponential is right-skewed, with many short waits and a few very long ones.

Theorem: Waiting Times in a Poisson Process

If events occur as a Poisson process with rate λ (Section 4.7), the waiting time T until the first event is Exp(λ).

The wait is longer than t exactly when there are no events in [0,t]. The number of events in that window is Pois(λt), so Pr(T>t)=Pr(no events in [0,t])=e−λt(λt)00!=e−λt, which is the exponential tail probability. ◼∎

So the Poisson and exponential distributions are two views of the same process: the Poisson counts events in a fixed time, the exponential measures time between events. With 911 calls at 4.5 per hour (Example 4.20), the gap between calls is Exp(4.5), with mean 14.5 hour ≈13.3 minutes, and Pr(gap>20 min)=e−4.5/3=e−1.5≈0.223, exactly the probability of no calls in 20 minutes that we found there.

Theorem: The Exponential Is Memoryless

If X∼Exp(λ), then for all s,t≥0, Pr(X>s+t∣X>s)=Pr(X>t).

{X>s+t} is contained in {X>s}, so Pr(X>s+t∣X>s)=Pr(X>s+t)Pr(X>s)=e−λ(s+t)e−λs=e−λt=Pr(X>t).◼∎

As for the geometric distribution (Section 4.5), past waiting tells you nothing about future waiting. If you've waited 30 minutes for a call, the remaining wait has the same distribution as if you'd just started. That's a strong assumption: it fits radioactive atoms and random arrivals, but not light bulbs or people, which wear out.

Example 5.9: British Coal-Mining Disasters ★ lecture example

R's boot package (installed with R) contains the dates of 191 explosions in British coal mines that killed 10 or more people, from 1851 to 1962. (a) For the disasters up to 1890, compute the gaps between consecutive disasters, in days, and check whether an exponential model fits. (b) Using the model, find the probability of a whole year without a disaster, and compare with the data. (c) What happened to the gaps after 1900?

(a) coal$date records each disaster as a decimal year. diff() gives the gaps between consecutive dates; multiplying by 365.25 converts to days.

R
library(boot)
gaps <- diff(coal$date) * 365.25            # days between disasters
early <- gaps[coal$date[-1] < 1890]         # gaps ending before 1890
length(early)
c(mean = mean(early), sd = sd(early), median = median(early))
output
[1] 122
    mean       sd   median 
115.5328 122.9763  80.5000 

Three quick checks for an exponential distribution, all passed:

  • The mean (115.5 days) and standard deviation (123 days) should be equal, since both are 1/λ. They nearly are.
  • The median should be ln2≈0.69 times the mean: 0.69×115.5≈80 days. The data's median is 80.5.
  • The histogram should follow the curve λe−λx with λ=1/115.5:
R
ggplot(data.frame(days = early), aes(days)) +
  geom_histogram(aes(y = after_stat(density)), binwidth = 50, boundary = 0, colour = "white") +
  stat_function(fun = dexp, args = list(rate = 1 / mean(early)), linewidth = 1) +
  labs(x = "days between disasters (1851 to 1890)", y = "density")
Density histogram of the 122 gaps between British coal-mining disasters before 1890, in…Density histogram of the 122 gaps between British coal-mining disasters before 1890, in days, from 0 to about 850 (one isolated gap of 826 days). The bars are tallest near zero and decline steadily, closely following an exponential density curve with mean 115.5 days drawn on top. 0.0000 0.0025 0.0050 0.0075 0 200 400 600 800 days between disasters (1851 to 1890) density

(b) With λ=1/115.5 per day, Pr(gap>365)=e−365/115.5≈0.042. In the data, 5 of the 122 gaps (4.1%) were longer than a year.

R
exp(-365 / mean(early))     # model
mean(early > 365)           # data
mean(gaps[coal$date[-1] >= 1900])   # (c) mean gap after 1900
output
[1] 0.04245645
[1] 0.04098361
[1] 408.2321

(c) After 1900, the average gap between disasters was about 408 days, more than three times as long. The rate of disasters fell sharply. A constant-rate exponential model fits each period, but not the whole century: the mechanism changed. Historians link the change to safety legislation, better ventilation and the decline of the most dangerous practices. (Whether the laws caused the drop is a causal question that needs more than these data: Chapter 1's DAGs again.)

Data: R. G. Jarrett (1979), "A note on the intervals between coal-mining disasters", Biometrika 66, 191–193.

Prediction and inference. Parts (a) and (b) are inference about the mechanism (disasters at a steady random rate, about one every 115 days) and a prediction from it (a disaster-free year about 4% of the time). Part (c) is the warning: a model fitted to 1851–1890 would have predicted the 1900s badly. Every prediction assumes the mechanism stays the same.

Explore the exponential distribution

Move the sliders to change the parameters. Press draw a random sample to simulate values from this distribution: their density histogram (orange) appears beneath the curve, and with a large sample it hugs the curve. Tick shade and move x to see Pr(X ≤ x) as an area, with the R command that computes it.

Density curve for the chosen parametersDensity curve for the chosen parameters. A random sample can be drawn and shown as a density histogram beneath the curve, and the area to the left of x can be shaded.

Example 5.10: How Old Is the Iceman? ★ lecture example

In 1991, hikers in the Alps found a frozen human body, now known as Ötzi the Iceman. Living things absorb carbon-14, a radioactive form of carbon, until they die; afterwards it decays. Each carbon-14 atom's lifetime is exponential, with a half-life of 5,730 years: the median lifetime. (a) Find the decay rate λ. (b) What fraction of the original carbon-14 remains after t years? (c) Ötzi's tissue contained about 53% of the carbon-14 found in living tissue. Estimate how long ago he died.

(a) The half-life is the median, ln2λ=5730, so λ=ln25730≈0.000121 per year. (The mean lifetime of an atom is 1/λ≈8,267 years, longer than the half-life, as for any exponential.)

(b) Each atom survives t years with probability Pr(X>t)=e−λt. With trillions of atoms, the Law of Large Numbers makes the fraction surviving essentially equal to this probability: fraction remaining=e−λt=(12)t/5730. After one half-life, half remains; after two, a quarter; after three, an eighth.

(c) Solve e−λt=0.53: take logs, −λt=ln0.53, so t=−ln0.53λ=0.6350.000121≈5,250 years.

R
lambda <- log(2) / 5730
lambda
-log(0.53) / lambda          # years since death
output
[1] 0.0001209681
[1] 5248.312

Ötzi died around 5,200 to 5,300 years ago, in the Copper Age, consistent with the radiocarbon dates that archaeologists published. (He had an arrowhead lodged in his shoulder: the oldest murder victim to be studied with modern forensic science.) The widget below shows the same process with 400 atoms: individual decays are completely unpredictable, but the fraction remaining is not.

R
t <- seq(0, 15000, by = 50)
ggplot(data.frame(t, frac = exp(-lambda * t)), aes(t, frac)) +
  geom_line(linewidth = 1) +
  annotate("segment", x = 0, xend = -log(0.53) / lambda, y = 0.53, yend = 0.53, linetype = "dashed") +
  annotate("segment", x = -log(0.53) / lambda, xend = -log(0.53) / lambda, y = 0, yend = 0.53, linetype = "dashed") +
  labs(x = "years since death", y = "fraction remaining")
Decay curve of the fraction of carbon-14 remaining against years since death, from 1 at…Decay curve of the fraction of carbon-14 remaining against years since death, from 1 at time 0 falling to 0.5 at 5,730 years and 0.25 at 11,460 years. Dashed lines mark the fraction 0.53 and the corresponding age of about 5,250 years. 0.00 0.25 0.50 0.75 1.00 0 5000 10000 15000 years since death fraction remaining

This is inference in its purest form: an unobservable quantity (the time since death) inferred from a measurement (the fraction remaining) through a probability model of the mechanism (exponential decay). Real radiocarbon dates also report an uncertainty, because the 53% is itself measured with error.

Radioactive decay, one atom at a time

Each of the 400 squares is a radioactive atom. Every atom's lifetime is exponential with the same half-life, independently of the others: no atom "knows" how old it is. Press let time pass and watch the atoms decay (they turn grey). The right panel tracks the fraction still undecayed against the exponential curve e−λt. Notice that the fraction halves in every half-life, whether it started at 100% or 25%.

Grid of 400 atoms, coloured if undecayed and grey if decayedGrid of 400 atoms, coloured if undecayed and grey if decayed. Fraction of atoms remaining against time, with the exponential curveFraction of atoms remaining against time, with the exponential curve.

The gamma distribution

The exponential is the wait for the first event. The wait for the rth event is a sum of r independent exponential gaps, and has a gamma distribution, just as the negative binomial was a sum of geometric waits.

Definition: Gamma Distribution

X has the gamma distribution with shape α>0 and rate λ>0, written X∼Gamma(α,λ), if f(x)=λαΓ(α)xα−1e−λx,x>0, where Γ(α)=∫0∞tα−1e−tdt is the gamma function (Γ(r)=(r−1)! for whole numbers r). Then E[X]=α/λ and Var[X]=α/λ2. The exponential is the case α=1; for a whole number α=r, X is the waiting time for the rth event of a Poisson process with rate λ.

The gamma is also a flexible model for any positive, right-skewed measurement (rainfall totals, insurance claims, hospital stays), whether or not it's literally a waiting time.

Example 5.11: The Third Call

911 calls arrive at 4.5 per hour. What is the probability that the third call of the afternoon arrives within 20 minutes? Answer it two ways.

As a waiting time. The wait T for the 3rd call is Gamma(3,4.5) (in hours), and we want Pr(T≤13): pgamma(1/3, shape = 3, rate = 4.5).

As a count. The 3rd call arrives within 20 minutes exactly when there are at least 3 calls in those 20 minutes. The count is Pois(4.5/3)=Pois(1.5), so Pr(T≤13)=1−Pr(N≤2)=1−e−1.5(1+1.5+1.522)≈1−0.809=0.191.

R
pgamma(1/3, shape = 3, rate = 4.5)
1 - ppois(2, 1.5)
output
[1] 0.1911532
[1] 0.1911532

Both give 0.191. Counting events and timing them are two descriptions of one process; whichever is easier to compute will do.

Explore the gamma distribution

Move the sliders to change the parameters. Press draw a random sample to simulate values from this distribution: their density histogram (orange) appears beneath the curve, and with a large sample it hugs the curve. Tick shade and move x to see Pr(X ≤ x) as an area, with the R command that computes it.

Density curve for the chosen parametersDensity curve for the chosen parameters. A random sample can be drawn and shown as a density histogram beneath the curve, and the area to the left of x can be shaded.

Check Yourself

Light bulbs in a hallway fail at random, with lifetimes exponential with mean 10 months. What is the probability a bulb lasts more than 10 months?

The same bulb has already lasted 10 months. What is the probability it lasts at least another 10?

Think About It: Memoryless or Not?

Which of these are plausibly memoryless (exponential), and which are not? (a) The time until a uranium atom decays. (b) A person's remaining lifetime. (c) The time until a car breaks down. (d) The time until the next customer enters a busy shop. For those that aren't, does the chance of the event in the next month go up or down with age?

(a) Memoryless: atoms have no internal clock, which is exactly what makes radiocarbon dating work. (b) Not: the chance of dying in the next year rises with age (after childhood), so lifetimes are better described by a Weibull or similar model with an increasing failure rate. (c) Mostly not: parts wear, so risk rises with age, though a new car may also have early "teething" failures. (d) Roughly memoryless over short periods, but the rate changes through the day, so a model with a constant λ only works for a short window. Choosing a model is a claim about the mechanism; the exponential claims there is no ageing at all.

Key Takeaways

  • Exponential Exp(λ): the wait for the first event of a Poisson process. Pr(X>x)=e−λx; mean 1/λ; median ln2/λ.
  • Memoryless: no wear and tear. Half-lives are exponential medians.
  • Gamma Gamma(α,λ): the wait for the αth event; mean α/λ. Counting events and timing them give the same answers.

5.5 The beta distribution: uncertain proportions

Some quantities are proportions: a player's true free-throw percentage, the fraction of a drug seizure that's genuine, the share of voters supporting a policy. They live between 0 and 1, and the beta distribution is the standard model for them.

Definition: Beta Distribution

X has the beta distribution with shape parameters α,β>0, written X∼Beta(α,β), if f(x)=Γ(α+β)Γ(α)Γ(β)xα−1(1−x)β−1,0<x<1. Its mean is E[X]=αα+β and its variance αβ(α+β)2(α+β+1). Beta(1,1) is the uniform distribution on [0,1].

The shape is very flexible: symmetric when α=β, piled up near 1 when α>β, near 0 when α<β, and more concentrated as α+β grows. Explore it:

Explore the beta distribution

Move the sliders to change the parameters. Press draw a random sample to simulate values from this distribution: their density histogram (orange) appears beneath the curve, and with a large sample it hugs the curve. Tick shade and move x to see Pr(X ≤ x) as an area, with the R command that computes it.

Density curve for the chosen parametersDensity curve for the chosen parameters. A random sample can be drawn and shown as a density histogram beneath the curve, and the area to the left of x can be shaded.

The beta distribution's most important job is in Bayesian statistics, as a description of what we know about an unknown proportion.

Bayesian Inference: Learning a Free-Throw Percentage

In Chapter 4's Bayesian box, we learned a success probability p from a grid of 11 candidate values. The beta distribution lets p be any value between 0 and 1. And it has a remarkable property: if your prior for p is Beta(α,β) and you observe s successes and f failures in independent trials, your posterior is Beta(α+s,β+f). The prior's parameters act like "imaginary" earlier successes and failures, and data simply add to them. (The proof multiplies the prior density by the binomial likelihood ps(1−p)f: the result has the beta form, with the exponents increased by s and f.)

Example. A new basketball player makes 7 of her first 10 free throws. Starting from a uniform prior, Beta(1,1), her posterior is Beta(8,4):

R
p <- seq(0, 1, by = 0.005)
d <- rbind(data.frame(p, density = dbeta(p, 1, 1), which = "prior Beta(1, 1)"),
           data.frame(p, density = dbeta(p, 8, 4), which = "posterior Beta(8, 4)"))
ggplot(d, aes(p, density, linetype = which)) + geom_line(linewidth = 1) +
  labs(x = "free-throw success probability p", y = "density", linetype = NULL)
8 / (8 + 4)                         # posterior mean
1 - pbeta(0.5, 8, 4)                # Pr(p > 0.5 | data)
qbeta(c(0.025, 0.975), 8, 4)        # middle 95% of the posterior
output
[1] 0.6666667
[1] 0.8867188
[1] 0.3902574 0.8907366
Two density curves for a free-throw success probability p between 0 and 1Two density curves for a free-throw success probability p between 0 and 1. The prior, Beta(1,1), is flat at height 1. The posterior after 7 makes in 10 attempts, Beta(8,4), is a hump peaking near 0.7, with most of its area between about 0.4 and 0.9. 0 1 2 3 0.00 0.25 0.50 0.75 1.00 free-throw success probability p density posterior Beta(8, 4) prior Beta(1, 1)

Her posterior mean is 812≈0.67, a little below her observed 70%, pulled slightly towards the prior's 50%. There's an 89% probability that she's better than a 50% shooter, and her true percentage is 95% likely to lie between 0.39 and 0.89: after only 10 shots, we know surprisingly little. After 100 shots the posterior would be much narrower. This "credible interval" is the Bayesian cousin of Chapter 8's confidence interval.

Think About It: What Does the Prior Do?

Two scouts watch the same new player make 7 of 10 free throws. One starts from a uniform prior, Beta(1,1); the other, who knows that most professional players make 70% to 80%, starts from Beta(15,5). Find each posterior mean. Whose estimate would you trust more after 10 shots, and after 1,000?

Posteriors: Beta(8,4) with mean 8/12≈0.67, and Beta(22,8) with mean 22/30≈0.73. After 10 shots the second scout's estimate is probably better, because her prior contains real information (the equivalent of 20 earlier shots) and 10 shots are very few. After 1,000 shots, the data overwhelm both priors: with, say, 700 makes the posteriors are Beta(701,301) and Beta(715,305), with means 0.700 and 0.701. A prior matters when data are scarce, and it should be based on evidence that can be stated and checked; with plenty of data, reasonable priors agree.

5.6 More shapes of chance

Log-Gaussian: when causes multiply

Some quantities grow by percentages: a river gathers tributaries that each enlarge it, a city grows by a few percent a year, a pollutant's concentration is diluted by successive factors. When many independent effects multiply, the logarithm of the result is a sum of many effects, and so (by the reasoning of the causal box in Section 5.3) approximately Gaussian.

Definition: log-Gaussian Distribution

X has the log-Gaussian distribution if lnX∼N(μ,σ2). Then X is positive and right-skewed, with median eμ and mean eμ+σ2/2, which is larger than the median. In R: plnorm(x, meanlog = mu, sdlog = sigma).

Example 5.12: How Long Is a River? ★ lecture example

R's rivers dataset gives the lengths, in miles, of 141 major rivers in North America (from the World Almanac, 1975). (a) Describe the distribution of lengths, and of their logarithms. (b) Fit a log-Gaussian model and use it to estimate the fraction of rivers longer than 1,000 miles. Compare with the data.

(a) The lengths are strongly right-skewed: most are a few hundred miles, but the Mississippi, Missouri and a few others run to thousands. On a log scale the skew largely disappears:

R
d <- rbind(data.frame(scale = "length (miles)", value = rivers),
           data.frame(scale = "log of length", value = log(rivers)))
ggplot(d, aes(value)) + geom_histogram(bins = 20, colour = "white") +
  facet_wrap(~ scale, scales = "free") + labs(x = NULL, y = "number of rivers")
Two histograms side by sideTwo histograms side by side. Left: lengths of 141 North American rivers in miles, piled up between 200 and 800 with a long right tail out to 3,710. Right: the natural logarithms of the same lengths, much more symmetric and bell-shaped, centred near 6.2. length (miles) log of length 0 1000 2000 3000 4000 5 6 7 8 0 5 10 15 20 0 20 40 number of rivers

(b) Fit a Gaussian to the logs: their mean is 6.18 and SD 0.59. Then Pr(X>1000)=Pr(lnX>ln1000)=1−Φ(6.908−6.1760.591)=1−Φ(1.24)≈0.108.

R
m <- mean(log(rivers)); s <- sd(log(rivers))
c(m, s)
1 - plnorm(1000, meanlog = m, sdlog = s)   # model
mean(rivers > 1000)                         # data: 16 of 141
exp(m); median(rivers)                      # model median vs data median
output
[1] 6.1758789 0.5914841
[1] 0.1079775
[1] 0.1134752
[1] 481.0056
[1] 425

The model gives 10.8%; the data, 11.3% (16 rivers). The model's median, e6.176≈481 miles, is a bit above the data's 425, a sign that the fit isn't perfect, but it captures the long tail far better than a Gaussian model could: a Gaussian with the data's mean (591) and SD (494) would give a 12% chance of a river with negative length.

Explore the log-Gaussian distribution

Move the sliders to change the parameters. Press draw a random sample to simulate values from this distribution: their density histogram (orange) appears beneath the curve, and with a large sample it hugs the curve. Tick shade and move x to see Pr(X ≤ x) as an area, with the R command that computes it.

Density curve for the chosen parametersDensity curve for the chosen parameters. A random sample can be drawn and shown as a density histogram beneath the curve, and the area to the left of x can be shaded.

In toxicology, drug and pollutant concentrations in the body are usually log-Gaussian, which is why toxicologists report geometric means and work on a log scale; ozone levels (Chapter 2) behave the same way.

Weibull: things that wear out

The exponential distribution says that a component's chance of failing next month doesn't depend on its age. Most things aren't like that: tyres, bones and hard drives wear out, so their failure rate rises with age; and some products fail early from manufacturing defects, so their failure rate falls. The Weibull distribution, with Pr(X>x)=e−(x/θ)k, handles both: shape k>1 means wearing out, k<1 means early failures, and k=1 is the exponential. Engineers use it for reliability, and medical researchers for survival times.

Explore the Weibull distribution

Move the sliders to change the parameters. Press draw a random sample to simulate values from this distribution: their density histogram (orange) appears beneath the curve, and with a large sample it hugs the curve. Tick shade and move x to see Pr(X ≤ x) as an area, with the R command that computes it.

Density curve for the chosen parametersDensity curve for the chosen parameters. A random sample can be drawn and shown as a density histogram beneath the curve, and the area to the left of x can be shaded.

Chi-squared and t: distributions for later

Two more distributions arise not as models of the world but from calculations on Gaussian data, and they'll be essential in Chapters 8 and 9.

Explore the chi-squared distribution

Move the sliders to change the parameters. Press draw a random sample to simulate values from this distribution: their density histogram (orange) appears beneath the curve, and with a large sample it hugs the curve. Tick shade and move x to see Pr(X ≤ x) as an area, with the R command that computes it.

Density curve for the chosen parametersDensity curve for the chosen parameters. A random sample can be drawn and shown as a density histogram beneath the curve, and the area to the left of x can be shaded.

Explore the t distribution

Move the sliders to change the parameters. Press draw a random sample to simulate values from this distribution: their density histogram (orange) appears beneath the curve, and with a large sample it hugs the curve. Tick shade and move x to see Pr(X ≤ x) as an area, with the R command that computes it. The dashed curve is the standard Gaussian: raise the degrees of freedom and watch the two merge.

Density curve for the chosen parametersDensity curve for the chosen parameters. A random sample can be drawn and shown as a density histogram beneath the curve, and the area to the left of x can be shaded.

History: Student, Who Worked at a Brewery

The t distribution was discovered by William Sealy Gosset, a chemist at the Guinness brewery in Dublin. Guinness needed to judge the quality of barley and hops from very small samples, and Gosset worked out how much the Gaussian distribution's predictions had to be widened when the standard deviation was estimated from just a handful of measurements. Guinness didn't allow its scientists to publish under their own names (after an earlier employee's paper had given away trade secrets, the company banned such publications), so his 1908 paper appeared under the pen name "Student", and the distribution has been "Student's t" ever since.

Think About It: Which Scale Should We Predict on?

A toxicologist reports that the average concentration of a pollutant in 50 water samples is 12 µg/L, but the median is 5 µg/L and the legal limit is 10. A water company says "typical water is well under the limit"; an activist says "on average the water is over the limit". Who is right? What summary would you report, and what would you want to predict?

Both are describing a right-skewed (probably log-Gaussian) distribution truthfully: most samples are low, but a few very high ones pull the mean up. Which summary matters depends on the question. For a person's long-run exposure, the mean is relevant, since high and low days average out over time. For the risk on a given day, we'd want the probability that a sample exceeds the limit, which a log-Gaussian model fitted to the logged data can estimate (as in Example 5.12). Report the median, the mean and the fraction over the limit, and show a histogram on a log scale. Neither single number tells the whole story.

5.7 Choosing a continuous model

Each named distribution has a characteristic shape. Seeing them side by side is the quickest way to match a model to a histogram. (The examples shown are a gamma with shape 3, a beta with parameters 2 and 5, a log-Gaussian with σ=0.6 and a Weibull with shape 2; changing the parameters changes the details, not the family resemblance.)

R
curves <- function(name, x, y) data.frame(model = name, x = x, y = y)
d <- rbind(
  curves("uniform", seq(-0.2, 1.2, by = 0.005), dunif(seq(-0.2, 1.2, by = 0.005))),
  curves("Gaussian", seq(-4, 4, by = 0.02), dnorm(seq(-4, 4, by = 0.02))),
  curves("exponential", seq(0, 5, by = 0.02), dexp(seq(0, 5, by = 0.02))),
  curves("gamma", seq(0, 10, by = 0.02), dgamma(seq(0, 10, by = 0.02), 3)),
  curves("beta", seq(0, 1, by = 0.005), dbeta(seq(0, 1, by = 0.005), 2, 5)),
  curves("log-Gaussian", seq(0, 5, by = 0.02), dlnorm(seq(0, 5, by = 0.02), 0, 0.6)),
  curves("Weibull", seq(0, 3, by = 0.01), dweibull(seq(0, 3, by = 0.01), 2)))
d$model <- factor(d$model, levels = unique(d$model))
ggplot(d, aes(x, y)) + geom_line(linewidth = 1) +
  facet_wrap(~ model, scales = "free", ncol = 3) +
  scale_x_continuous(n.breaks = 3) + scale_y_continuous(n.breaks = 3) +
  labs(x = NULL, y = "density")
Seven small density plots in a grid of three columnsSeven small density plots in a grid of three columns. Uniform: a flat line. Gaussian: a symmetric bell. Exponential: highest at zero and decaying. Gamma (shape 3): rising from zero to a peak and then a long right tail. Beta(2, 5): a hump between 0 and 1, skewed right. Log-Gaussian: a right-skewed hump with a long tail. Weibull (shape 2): a hump rising from zero, less skewed than the gamma. Weibull gamma beta log-Gaussian uniform Gaussian exponential 0 1 2 3 0 5 10 0.0 0.5 1.0 0.0 2.5 5.0 0 1 0 0.0 2.5 5.0 0.0 0.5 1.0 0.0 0.4 0.8 0.0 0.2 0.4 0 1 2 0.0 0.5 1.0 0.0 0.1 0.2 0.0 0.5 density
distribution the story values mean
Unif(a,b) equally likely anywhere in an interval [a,b] a+b2
N(μ,σ2) sums of many small independent effects; measurement error all real numbers μ
Exp(λ) wait for the first random event; no ageing x≥0 1λ
Gamma(α,λ) wait for the αth event; positive skewed amounts x>0 αλ
Beta(α,β) an uncertain proportion (0,1) αα+β
log-Gaussian products of many effects; concentrations, sizes x>0 eμ+σ2/2
Weibull lifetimes with wear-out or early failure x≥0

Every distribution has d, p, q and r functions in R, exactly as in Chapter 4, named after its short name: unif, norm, exp, gamma, beta, lnorm and weibull (for example dexp, pexp, qexp, rexp).

Idea: Algorithm: Which Continuous Model?

  1. What values are possible? All real numbers (Gaussian, t); positive only (exponential, gamma, log-Gaussian, Weibull); between 0 and 1 (beta); a fixed interval (uniform).
  2. What mechanism produced it? Many small additive effects: Gaussian. Multiplicative effects: log-Gaussian. Waiting for random events: exponential or gamma. Wear-out: Weibull.
  3. Look at the data: a histogram, and a Q-Q plot against the candidate model.
  4. Check the claims you care about. A model can fit the middle and fail in the tails, which is often exactly where the important questions are.

Check Yourself

Prediction and inference in this chapter

5.8 Interludes

Interlude (Optional): The Cauchy Distribution: When Averages Fail

A lighthouse stands 1 mile off a straight coast and rotates at a steady speed, sending out brief flashes at uniformly random angles. Where along the coast do the flashes hit? If the angle is Θ∼Unif(−π2,π2), the flash hits the coast at X=tanΘ. This X has the Cauchy distribution, with density f(x)=1π(1+x2),−∞<x<∞. It looks like a bell curve centred at 0, a little lower and wider. But its tails fall off so slowly (like 1/x2, not like e−x2) that the integral ∫|x|f(x)dx is infinite: the Cauchy distribution has no expected value. When the beam is nearly parallel to the coast, the flash lands enormously far away, and those rare enormous values dominate any average.

The consequence is startling: the Law of Large Numbers fails. The average of n Cauchy draws has exactly the same Cauchy distribution as a single draw, however large n is. Averaging doesn't help at all.

An average that never settles

Both distributions are symmetric bell-like curves centred at 0. The Gaussian running average settles towards 0, as the Law of Large Numbers promises. The Cauchy running average keeps lurching: every so often a single enormous value drags it somewhere new. Add more draws and see whether it ever calms down.

Running averages of Gaussian and Cauchy draws against the number of drawsRunning averages of Gaussian and Cauchy draws against the number of draws.

Why it matters: the Law of Large Numbers and the Central Limit Theorem need a finite mean (and variance). Real data with extremely heavy tails (insurance losses from catastrophes, the sizes of internet traffic bursts, losses in financial crashes) can behave more like the Cauchy than the Gaussian, and averages of such data are much less trustworthy than the Gaussian theory suggests.

Interlude (Optional): Families of Distributions

Many of this chapter's distributions come in families built from one basic shape.

  • Location–scale families. If Z has some standard distribution, then X=μ+σZ has the same shape, shifted by μ and stretched by σ. The Gaussian family is one (Z∼N(0,1)); so are the uniform, Cauchy and t families. Standardizing (Z=(X−μ)/σ) works for any location–scale family, and probabilities for every member come from one table for Z.
  • Exponential families. Most of the named distributions in Chapters 4 and 5 (binomial, Poisson, geometric, Gaussian, exponential, gamma, beta) can be written in a common form f(x∣θ)=h(x)exp(η(θ)T(x)−A(θ)), for suitable functions h, η, T and A. For the Poisson, for example, e−λλxx!=1x!exp(xlnλ−λ), with T(x)=x. This shared form is why they have so many properties in common: simple sufficient statistics (Chapter 8), conjugate Bayesian priors like the beta–binomial pair, and the unified "generalized linear models" used throughout applied statistics and machine learning (logistic regression is built on the Bernoulli family).

Why it matters: recognizing the family a distribution belongs to tells you, at once, many of the tools that will work for it.

5.9 Exercises

Each exercise has a hint and an answer. Draw a picture of the density and shade the area you want before calculating.

Exercises

  1. A density by hand. The time X (in hours) that a lab takes to process an urgent sample has density f(x)=c(4−x) for 0≤x≤4. (a) Find c. (b) Find Pr(X≤1). (c) Find E[X]. (d) Find the median.

    The density is a triangle with base 4 and height 4c. For (d), the CDF is F(x)=c(4x−x2/2); set it equal to 12 and solve the quadratic.

    (a) ∫04c(4−x)dx=8c=1, so c=18. (b) F(1)=18(4−12)=716≈0.4375. (c) ∫04x4−x8dx=18(32−643)=43 hours. (d) 18(4m−m2/2)=12 gives m2−8m+8=0, so m=4−22≈1.17 hours.

  2. Uniform. A random number generator produces U∼Unif(0,10). (a) Find Pr(3≤U≤7). (b) Find E[U] and SD[U]. (c) Find Pr(U=5), and explain why it isn't a problem that it equals what it does.

    For a uniform distribution, probabilities are lengths divided by the total length.

    (a) 7−310=0.4. (b) Mean 5, SD 100/12≈2.89. (c) 0: a single point has no length. Every particular value has probability zero, but intervals don't, and some value always occurs.

  3. Galton's daughters. Galton's 453 daughters had mean height 64.1 inches and SD 2.4 inches. Using a Gaussian model, find (a) the fraction taller than 68 inches, (b) the fraction between 62 and 66 inches, and (c) the height that only 10% of daughters exceed. (d) Check (a) against the data.

    Standardize each value. For (d), with galton loaded as in Example 5.1, compute mean(galton$childHeight[galton$gender == "female"] >= 68).

    (a) z=(68−64.1)/2.4=1.625; 1−Φ(1.625)≈0.052. (b) Φ(0.792)−Φ(−0.875)≈0.786−0.191=0.595. (c) 64.1+1.2816×2.4≈67.2 inches. (d) The data give 0.071, more than the model predicts, but almost all of the excess is heaping: 13 daughters were recorded at exactly 68 inches, which "≥68" includes; only 4.2% were recorded above 68.

  4. Low birth weight. In MASS::birthwt, birth weights have mean 2,945 g and SD 729 g. (a) Using a Gaussian model, estimate the fraction of babies under 2,500 g. (b) Compare with the data. (c) Why might a Gaussian model underestimate this fraction?

    Standardize 2,500. For (b), mean(MASS::birthwt$bwt < 2500). For (c), think about the shape of the left tail: what kinds of babies are very light?

    (a) Φ(2500−2945729)=Φ(−0.61)≈0.271. (b) The data give 0.312 (59 of 189). (c) Low weights come partly from a separate group (premature births) added to the main bell, so the left tail is heavier than a single Gaussian allows. Also, this hospital sample over-represented high-risk pregnancies. Models are often weakest in the tails, where the medically important cases are.

  5. IQ. IQ scores are designed to be N(100,152). (a) What fraction of people score above 130? (b) What score puts someone in the top 1%? (c) In a city of 8 million, about how many people would you expect to score above 160?

    (a) z=2; (b) qnorm(0.99, 100, 15); (c) multiply 8 million by Pr(Z>4).

    (a) 1−Φ(2)≈0.023. (b) 100+2.326×15≈134.9. (c) Pr(Z>4)≈3.2×10−5, so about 8,000,000×0.000032≈250 people, though IQ tests aren't designed to measure accurately that far into the tail.

  6. Exponential waits. Customers arrive at a pharmacy's prescription counter at an average rate of 12 per hour, independently. (a) What is the distribution of the time between arrivals, and its mean in minutes? (b) What is the probability of a gap of more than 10 minutes? (c) What is the median gap?

    The gap is Exp(12) in hours, or Exp(0.2) in minutes.

    (a) Exp(0.2) per minute; mean 5 minutes. (b) e−0.2×10=e−2≈0.135. (c) ln2/0.2≈3.47 minutes.

  7. Carbon dating. A wooden tool contains 30% of the carbon-14 that living wood contains. Using a half-life of 5,730 years, how old is it?

    Solve (12)t/5730=0.30 by taking logs.

    t=5730×ln0.30ln0.5≈5730×1.737≈9,950 years.

  8. Memorylessness. A website's server crashes at random, at an average rate of once every 30 days, as a Poisson process. It has now run for 45 days without a crash. (a) What is the probability it runs at least another 30 days? (b) A manager says: "It's been 45 days, so a crash is overdue." Explain the mistake. (c) When would the manager's reasoning be correct?

    The time to a crash is exponential with mean 30 days. Use the memoryless property.

    (a) e−30/30=e−1≈0.368, the same as for a brand-new server. (b) Under the exponential model, the past 45 days are irrelevant; nothing is "due" (the gambler's fallacy again). (c) If crashes came from wear (memory leaks, filling disks), the failure rate would rise with time since the last restart, and a Weibull with shape k>1 would be a better model; then a long run would make a crash more likely.

  9. Gamma. Using Example 5.11's setting (911 calls at 4.5 per hour), find (a) the expected waiting time until the 5th call, and (b) the probability that the 5th call arrives within half an hour, in two ways.

    T∼Gamma(5,4.5). Alternatively, the 5th call arrives within half an hour if there are at least 5 calls in that half hour, a Pois(2.25) count.

    (a) 5/4.5≈1.11 hours, about 67 minutes. (b) pgamma(0.5, 5, 4.5) = 1 - ppois(4, 2.25) ≈0.078.

  10. Beta update. A forensic lab has tested 20 randomly chosen pills from a seizure and found that 12 contain fentanyl. (a) Starting from a uniform prior for the proportion p of fentanyl pills, what is the posterior distribution? (b) Find the posterior mean. (c) Find the posterior probability that more than 60% of the pills contain fentanyl.

    Beta prior (1,1) plus 12 successes and 8 failures. Use 1 - pbeta(0.6, a, b).

    (a) Beta(13,9). (b) 1322≈0.59. (c) 1 - pbeta(0.6, 13, 9) ≈0.48: given the data, it's roughly a coin flip whether more than 60% of the pills contain fentanyl. Twenty pills can't pin the proportion down.

  11. Log-Gaussian. Blood concentrations of a drug, one hour after a standard dose, are log-Gaussian with median 4 mg/L, and their natural logarithms have SD 0.5. (a) What is μ for the log concentrations? (b) What fraction of patients exceed 10 mg/L, a toxic level? (c) Why is the mean concentration higher than the median?

    The median of a log-Gaussian is eμ. Then Pr(X>10)=1−Φ(ln10−μ0.5).

    (a) μ=ln4≈1.386. (b) z=(2.303−1.386)/0.5≈1.83; 1−Φ(1.83)≈0.034, about 3.4% of patients. (c) The distribution is right-skewed: a few patients with very high concentrations pull the mean (eμ+σ2/2=4e0.125≈4.53) above the median.

  12. Simulation by inverse transform. (a) Show that if U∼Unif(0,1), then X=−1λln(1−U) is Exp(λ). (b) Use this in R, without rexp(), to simulate 10,000 waits with λ=2, and check their mean.

    Solve u=F(x)=1−e−λx for x. In R: u <- runif(10000); x <- -log(1 - u) / 2.

    (a) u=1−e−λx gives x=−1λln(1−u), which is F−1(u); by the inverse transform theorem, F−1(U) has CDF F. (b) mean(-log(1 - runif(10000)) / 2) is close to 1/2.

  13. Gaussian approximation. A coin is flipped 400 times. (a) Use the Gaussian approximation with continuity correction to estimate the probability of 220 or more heads. (b) Compare with the exact binomial. (c) Would 220 heads make you doubt that the coin is fair?

    Mean 200, SD 400×0.25=10. "220 or more" becomes "above 219.5".

    (a) z=(219.5−200)/10=1.95; 1−Φ(1.95)≈0.026. (b) 1 - pbinom(219, 400, 0.5) ≈0.026. (c) Somewhat: a fair coin gives 220 or more heads only about 2.6% of the time (or 5% for a result that far from 200 in either direction). Chapter 9 turns this reasoning into a formal test.