Continuous random variables — practice in R with a simulated microwave queue, three lunchboxes that add up to a gamma and a model fitted to data (and the rgamma that gave me times four times too short)

I simulated the wait with three people ahead thinking that the 2 in rgamma(10000, 3, 2) meant two minutes per person, and I got waits four times too short. A mean of 1.5 minutes instead of 6, and R did not complain at all. The third argument of rgamma is the rate, not the mean, and I had told it that each person took half a minute. Since that day I check every simulation against the theoretical mean before believing any number, and that is what you are going to do in this practice.

This practice puts on the computer what we saw in the continuous random variables theory and its proofs. There are three intermediate programs with the cafeteria microwave: simulating ten thousand arrivals in the queue and comparing them with the exponential, checking that three waits in a row add up to a gamma, and fitting a model to sixty heating times written down by hand. The data look like real data: times with decimals, a long right tail and a “textbook” model that does not fit what you see.

Before you start

It helps to be clear about:

  • For a continuous variable, probability is an area: p… and integrate, not d….
  • R’s parameters: dexp(x, rate), dgamma(x, shape, rate) (or scale = 1/rate) and dbeta(x, shape1, shape2).
  • The sum of α\alpha independent exponentials with rate β\beta is a gamma(α,β)\text{gamma}(\alpha, \beta), with mean α/β\alpha/\beta and variance α/β2\alpha/\beta^2.
  • hist(…, freq = FALSE): the heights of the bars are densities, so the theoretical curve can go on top.

If any of these feels shaky, review the theory before you go on.

Every program starts with set.seed(2026). That way, if you run the code as it is, in the site’s R playground or in RStudio, you get exactly the same numbers as here. If you remove that line, each run gives a different simulation (and slightly different decimals).

Program 1: ten thousand arrivals in the queue

If people really arrive at the microwave at a rate of one every 2 minutes, without memory, the times between arrivals are exp⁡(0.5)\exp(0.5). This program simulates ten thousand of those times and checks, number by number, that they behave as the theory says: the mean, the variance, the median, two probabilities and memorylessness. What makes it tricky is that the simulation never gives exactly the theoretical value, and you have to know when a difference is noise and when it is a mistake.

The idea

First the times are generated with rexp. Then each theoretical property is compared with its version “counted” in the data: the theoretical mean with mean, a probability with the proportion of data meeting the condition (mean(t < 1) is the proportion of times below 1, because t < 1 is a vector of TRUE/FALSE and R counts each TRUE as 1). For memorylessness, we keep only the times that are already over 3 and look at what proportion is over 5. Finally, the histogram with the density on top.

Before programming, think about what you expect to see: mean near 2, variance near 4, median near 1.39 and a histogram that starts high at 0 and falls. If something comes out far off, suspect the parameter before the theory.

Before launching ten thousand, look at what happens with six. The first six times rexp gives with seed 2026 are 0.79, 0.23, 3.01, 1.67, 0.22 and 8.15 minutes. Each line of the program asks them a yes-or-no question:

Timet < 1t > 3Why
0.79TRUEFALSEarrives in under a minute: counts towards P(T<1) P(T < 1)
0.23TRUEFALSEanother one who arrives right away
3.01FALSETRUEgets through the long_ones filter by one hundredth
1.67FALSEFALSEneither fast nor long
0.22TRUEFALSEthe third fast one
8.15FALSETRUEone from the tail: also over 5

With these six, mean(t < 1) would be 3/6 = 0.5: R turns TRUE into 1 and FALSE into 0, and the mean is counting and dividing. long_ones would hold two times, 3.01 and 8.15, and only the second goes over 5: mean(long_ones > 5) would be 1/2. With six data points the numbers jump around (0.5 against the theoretical 0.3935); with ten thousand, they settle. That is the whole program: the same question many times, and counting.

The code

set.seed(2026)
t <- rexp(10000, rate = 0.5)        # 10,000 times between arrivals: rate 0.5 per minute
# 1. The simulation's summaries versus the theoretical ones
round(c(mean = mean(t), variance = var(t), median = median(t)), 2)
round(c(mean = 1 / 0.5, variance = 1 / 0.5^2, median = qexp(0.5, 0.5)), 2)
# 2. Two probabilities: counted (proportion of TRUE) versus pexp
round(c(simulated = mean(t < 1), theoretical = pexp(1, 0.5)), 4)
round(c(simulated = mean(t > 5), theoretical = 1 - pexp(5, 0.5)), 4)
# 3. Memorylessness: of those already over 3, how many go over 5?
long_ones <- t[t > 3]               # keep only the waits that have already lasted 3 minutes
length(long_ones)
round(c(over_5_given_3 = mean(long_ones > 5), over_2 = mean(t > 2)), 4)
# 4. Density-scale histogram and the theoretical curve on top
hist(t, breaks = seq(0, ceiling(max(t)), by = 0.5), freq = FALSE, xlim = c(0, 12),
     main = "Time between arrivals", xlab = "minutes", ylab = "density")
curve(dexp(x, 0.5), add = TRUE, lwd = 2, col = "red")

Output

    mean variance   median 
    2.06     4.12     1.44 
    mean variance   median 
    2.00     4.00     1.39 
  simulated theoretical 
     0.3867      0.3935 
  simulated theoretical 
     0.0876      0.0821 
[1] 2358
over_5_given_3         over_2 
        0.3715         0.3815 
Histogram of 10,000 arrivals with the exponential on topDensity-scale histogram of 10,000 simulated exponential times, with half-minute bars from 0 to 12: the first is 0.44 tall and they fall like the red curve of the exponential density with rate 0.5, which starts at 0.5.0.00.10.20.30.40.5024681012minutesdensitydexp(x, 0.5)Time between arrivals10,000 simulated, 0.5 bars
Redrawn with the site colours: the bars of the simulated data closely follow the theoretical curve.

The numbers match the theory. The simulated mean is 2.06 (theoretical 2), the variance 4.12 (theoretical 4) and the median 1.44 (theoretical 1.39). The probability that someone arrives within a minute comes out as 0.3867 by counting and 0.3935 with pexp; that of waiting more than 5, 0.0876 versus 0.0821. These are differences of a few thousandths, the size you expect with ten thousand data points. In the drawing, the bars follow the red curve closely: they start at 0.44 (the curve is 0.5 at 0 and the first bar averages from 0 to 0.5) and fall just like the exponential.

How to read it

  • The first row is the summary of the 10,000 times; the second, the theoretical one. Comparing them is the proof that the parameter is right: had we written rate = 2, the simulated mean would be 0.5 and the gap with 2 would jump out.
  • mean(t < 1) is a relative frequency: 3,867 of the 10,000 times are below 1. By the law of large numbers (topic 7), that proportion gets close to P(T<1)P(T < 1) when there is a lot of data.
  • length(long_ones): 2,358 waits go over 3 minutes (23.6%; the theory says e−1.5=22.3e^{-1.5} = 22.3%).
  • Memorylessness: of those 2,358, 37.15% go over 5 minutes, that is, wait 2 more minutes. And of all the waits, 38.15% go over 2 minutes. The two proportions are almost the same: having already waited 3 minutes does not change what is left. The theory says both are e−1=0.3679e^{-1} = 0.3679.
  • The histogram is on the density scale (freq = FALSE): the height of each bar is the proportion of data in it divided by its width (0.5). That is why dexp, which is also a density, can go on top. With freq = TRUE (what hist does by default), the vertical axis would show counts (up to 2,188 in the first bar) and the curve would be flattened against the floor.

Memorylessness, count by count

The long_ones line computes a conditional probability in two steps. With counts instead of proportions it is easier to see:

GroupCountProportionTheoryWhy
All the waits10,00011the starting point
Over 3 (long_ones)2,3580.2358e−1.5=0.2231 e^{-1.5} = 0.2231 the filter: only those who have already waited 3 minutes
Of those, over 5876876/2358=0.3715 876/2358 = 0.3715 e−1=0.3679 e^{-1} = 0.3679 you divide by 2,358, not by 10,000: that is what conditioning means
Over 2, from scratch3,8150.3815e−1=0.3679 e^{-1} = 0.3679 the comparison: 2 minutes without having waited before

The 876 are all the waits longer than 5 minutes: anyone over 5 was already over 3. That is why the theory is a ratio, P(T>5∣T>3)=e−0.5⋅5/e−0.5⋅3=e−0.5⋅2 P(T > 5 \mid T > 3) = e^{-0.5 \cdot 5}/e^{-0.5 \cdot 3} = e^{-0.5 \cdot 2} . The 3 disappears and only what is left to wait remains.

Check you’ve got it: of the 876 waits over 5 minutes, what proportion do you expect to go over 7?

Close to 0.3679 again. Having waited 5 minutes is like having waited 3: all that matters is that 2 more are left, and the theory gives e−0.5⋅2=e−1 e^{-0.5 \cdot 2} = e^{-1} . In the simulation, 340 of the 876 go over 7: 0.3881. It drifts a bit further than the 0.3715 because it comes from 876 data points, not 2,358: less data, more noise.

Questions you might ask

Why is the simulated mean not exactly 2? Because it is the mean of a sample. With 10,000 data points, the simulated mean moves around 2 with a standard deviation of σ/n=2/100=0.02\sigma/\sqrt{n} = 2/100 = 0.02. A 2.06 is three of those standard deviations away: a bit high, but possible. With another seed you would get another similar value.

Why t[t > 3] and not t > 3? t > 3 is a vector of 10,000 TRUE/FALSE values. Putting it inside the brackets, t[…] keeps only the elements where it is TRUE: it is a filter. long_ones has 2,358 times, all greater than 3.

Why seq(0, ceiling(max(t)), by = 0.5) for the breaks? So that all bars are half a minute wide and start at 0. ceiling(max(t)) rounds the longest time (18.1 minutes) up, so the last break covers it; if a data point falls outside the breaks, hist gives an error.

What happens in the tail, beyond 10 minutes? There is very little data (a few dozen points), and the bars move around the curve more. The xlim = c(0, 12) cuts the drawing where nothing is visible any more, but the data are still there and count in the mean.

Comparing the histogram with the curve without freq = FALSE. The bars come out as counts (hundreds or thousands), the curve as density (below 1), and it looks as if the model does not fit at all. It is not the model: they are two different scales.

Try it yourself

  • Change the rate to 2 people per minute (rate = 2): the mean should drop to 0.5 and the median to 0.35. Also check memorylessness with t[t > 1] and mean(long_ones > 1.5).
  • Repeat the program with n = 100 instead of 10,000 and see how much further the simulated mean and probabilities now move away from the theoretical ones.

Program 2: three lunchboxes that add up to a gamma

Now there are three people ahead, and what each one takes is exponential with a mean of 2 minutes. The theory says the total wait is a gamma(3,0.5)\text{gamma}(3, 0.5). This program checks it by adding three simulated exponentials and comparing with pgamma and qgamma. And, along the way, it reproduces my mistake from the opening so you can see how to catch it.

The idea

Three vectors of 10,000 exponentials are generated and added element by element: the first wait of the first person plus the first of the second plus the first of the third, and so on. Each sum is a total wait. Then they are compared: mean and variance (6 and 12), a probability and two quantiles. Finally, gammas are generated directly with rgamma, once with the parameter wrong and once right, to see which one fits.

Before programming, think about what changes from program 1: the total wait can no longer be almost 0 (all three would have to be super quick at once), so the histogram should start low, climb to a peak around 4 (the mode, (3−1)/0.5(3 – 1)/0.5) and fall.

“Element by element”, with the first four rows of the simulation:

RowFirst personSecondThirdww <= 5?Why
10.790.011.131.94Yesall three fast
20.230.051.161.43Yessame: you eat right away
33.014.260.457.73Notwo slow ones in a row
41.677.510.189.37Noone very slow person is enough to go over

The first column is the 0.79, 0.23, 3.01 and 1.67 from program 1: same seed, and the first rexp is the first one to run. R adds with all the decimals, which is why 0.79 + 0.01 + 1.13 comes out as 1.94 and not 1.93.

The code

set.seed(2026)
n <- 10000
w <- rexp(n, 0.5) + rexp(n, 0.5) + rexp(n, 0.5)   # three waits in a row, added one by one
# 1. Mean and variance: the gamma(3, 0.5) says 6 and 12
round(c(mean = mean(w), variance = var(w)), 2)
# 2. Eating within 5 minutes: counted versus pgamma
round(c(simulated = mean(w <= 5), theoretical = pgamma(5, 3, 0.5)), 4)
# 3. The median and the 90% quantile: from the data versus qgamma
round(quantile(w, c(0.5, 0.9)), 2)
round(qgamma(c(0.5, 0.9), 3, 0.5), 2)
# 4. The mistake from the opening: the third argument is the RATE
wrong <- rgamma(n, 3, 2)                   # rate 2: each person, half a minute
right <- rgamma(n, shape = 3, scale = 2)   # scale 2: each person, 2 minutes
round(c(wrong = mean(wrong), right = mean(right)), 2)
# 5. Histogram of the sum with the gamma density on top
hist(w, breaks = seq(0, ceiling(max(w)), by = 1), freq = FALSE, xlim = c(0, 25),
     main = "Wait with three people ahead", xlab = "minutes", ylab = "density")
curve(dgamma(x, 3, 0.5), add = TRUE, lwd = 2, col = "red")

Output

    mean variance 
    6.01    12.01 
  simulated theoretical 
     0.4546      0.4562 
  50%   90% 
 5.38 10.67 
[1]  5.35 10.64
wrong right 
 1.51  5.95 
The sum of three exponentials and the gamma(3, 0.5)Density-scale histogram of 10,000 sums of three exponentials, with one-minute bars: the first is 0.016 tall, the peak is between 3 and 5 minutes, at 0.136, and the tail reaches 25. On top, the red curve of the gamma density with shape 3 and rate 0.5.0.000.050.100.150510152025minutesdensitydgamma(x, 3, 0.5)Wait with three people aheadsum of 3 rexp, 1-minute bars
Redrawn with the site colours: the sum of three waits no longer starts high at 0, like the exponential, but climbs to a peak.

The sum of three exponentials has mean 6.01 and variance 12.01: those of the gamma(3, 0.5). The probability of waiting 5 minutes or less comes out as 0.4546 by counting and 0.4562 with pgamma. The quantiles of the data (5.38 and 10.67) and those of qgamma (5.35 and 10.64) differ by a few hundredths. And the trap: with rgamma(n, 3, 2) the mean is 1.51 (3/23/2); with scale = 2, 5.95 (3⋅23 \cdot 2). In the drawing, the bars of the sum follow the gamma curve, which starts at 0, peaks at 4 minutes and has a long tail beyond 20.

How to read it

  • mean(w) and var(w): 6.01 and 12.01. They are 3⋅23 \cdot 2 and 3⋅43 \cdot 4: the mean and variance of a sum of independent variables are the sums of the means and of the variances (proved in topic 5). The gamma says it with α/β=3/0.5\alpha/\beta = 3/0.5 and α/β2=3/0.25\alpha/\beta^2 = 3/0.25.
  • quantile(w, …) returns a named vector: 50% is the median of the data and 90%, the value below which 90% of the waits fall. The row below, without names, is the theoretical quantiles from qgamma. Their near match is the best proof that the whole distribution fits, not just the mean.
  • wrong versus right: 1.51 versus 5.95. With the theoretical mean in front of you (6), the mistake stands out. Without it, 1.51 minutes of queue looks like a reasonable number, and that is why I believed it.
  • The histogram: one-minute bars on the density scale. The first bar (0 to 1) is very low (0.016): all three taking under a minute in total is rare. The peak is in the bars from 3 to 5 minutes.

The probability of eating within 5 minutes, by hand

With a whole-number α=3 \alpha = 3 , pgamma can be checked without integrating. Eating within 5 minutes means that all three people have finished in those 5 minutes. If they finish at a rate of 0.5 per minute, how many finish in 5 minutes is a Poisson with mean 0.5⋅5=2.5 0.5 \cdot 5 = 2.5 . The bad cases are 0, 1 or 2 finishing:

Finish in 5 minCalculationProbabilityWhy
0e−2.5 e^{-2.5} 0.0821nobody has finished: it is the P(T>5) P(T > 5) from program 1
12.5⋅e−2.5 2.5 \cdot e^{-2.5} 0.2052only the first one
22.522⋅e−2.5 \frac{2.5^2}{2} \cdot e^{-2.5} 0.2565the third is still with their lunchbox
Sum0.5438all the ways of not eating in time

What is left, 1−0.5438=0.4562 1 – 0.5438 = 0.4562 , is the pgamma(5, 3, 0.5) in the output (in R, also 1 - ppois(2, 2.5)). The simulation counted 0.4546: noise.

Check you’ve got it: what proportion of the 10,000 simulated waits goes over 10.64 minutes?

Roughly one in ten. 10.64 is the gamma’s 90% quantile: it leaves 90% of the probability below it and 10% above. In the simulation, mean(w > 10.64) gives 0.1011. That is why the data’s 90% quantile (10.67) comes out slightly higher: there is a touch more than 10% of the waits in that tail.

Questions you might ask

Why add three rexp instead of doing 3 * rexp(n, 0.5)? Because it is not the same. 3 * rexp(…) is a single wait multiplied by three: if the first person is quick, “all three” are quick at once. Its mean is also 6, but its variance is 9⋅4=369 \cdot 4 = 36, not 12. Adding three independent ones lets some make up for others, and the sum varies less.

How do I know whether a number in an R function is a rate or a scale? Type ?rgamma and look at the usage line: rgamma(n, shape, rate = 1, scale = 1/rate). If you pass the number without a name, it goes to rate. If you name it (scale = 2), there is no doubt. My advice: for the gamma, always name the argument.

And if it were not three people, but a random number? Then the wait would no longer be a gamma, but a mixture of gammas (one for each possible number of people, weighted by its probability). It is the idea of proof 5, with more branches.

What is the 90% quantile good for in real life? For planning: if you leave class with 11 minutes to eat, 90% of the time you will have time to heat your food with three people ahead. Means tell you what is typical; quantiles, how much margin to leave.

Using rgamma(n, 3, 2) when the 2 is the mean of each step. The third positional argument is the rate. Write scale = 2 or rate = 0.5, with the name.

Try it yourself

  • Simulate the wait with five people ahead and check that the mean is 10 and the variance 20. Where does the histogram peak now?
  • Compute var(3 * rexp(n, 0.5)) and compare it with var(w): check that it comes out near 36 and not 12.

Program 3: which model do the heating times follow?

In the theory we used a toy model for the time each person sets for their lunchbox: the line f(t)=t/8f(t) = t/8 between 0 and 4. But one lunchtime I wrote down the 60 times people set (they are in the code). Does the line fit? This program fits a gamma to those data by matching its mean and variance with those of the sample (the method the exam asks for in its “find the parameters with R” part) and compares both models with what you see.

The idea

A gamma has mean α/β\alpha/\beta and variance α/β2\alpha/\beta^2. If we set them equal to the mean mm and variance s2s^2 of the data and solve, we get β=m/s2\beta = m/s^2 and α=m2/s2\alpha = m^2/s^2 (it is the method of moments, which you will see properly in topic 9). With those parameters, we compare three things with the data: the probability of going over 3 minutes, the quartiles and the histogram with both densities on top.

Before programming, look at the data: there are values of 0.8 and 4.6, most of them between 1 and 3. A line that rises all the way to 4 puts a lot of probability near 4: does that match what you see?

Solving takes two steps. If you divide the mean by the variance, α \alpha goes away: α/βα/β2=β \frac{\alpha/\beta}{\alpha/\beta^2} = \beta . With β \beta known, the mean gives α=m⋅β \alpha = m \cdot \beta , which is the same as m2/s2 m^2/s^2 . With the numbers from the output:

StepCalculationResultWhy
Meanmean(times)2.175first equation: α/β=2.175 \alpha/\beta = 2.175
Variancevar(times)0.859second: α/β2=0.859 \alpha/\beta^2 = 0.859
Rate2.175/0.859 2.175/0.859 2.53dividing one equation by the other removes α \alpha
Shape2.175⋅2.5334 2.175 \cdot 2.5334 5.51from α/β=m \alpha/\beta = m you get α=m⋅β \alpha = m \cdot \beta
Check5.51/2.53 5.51/2.53 2.18it gives the mean back: if not, you solved it wrong

Multiply with the unrounded β \beta (2.5334) and round at the end. With 2.53 you would get α=5.50 \alpha = 5.50 instead of 5.51.

The code

times <- c(1.9, 2.9, 2.5, 1.0, 0.9, 1.1, 2.2, 1.3, 2.8, 2.6, 1.4, 1.9, 1.5, 2.9, 2.5,
           1.0, 3.0, 1.9, 2.3, 3.6, 1.7, 2.5, 3.2, 2.2, 1.4, 0.9, 3.4, 3.1, 2.6, 4.0,
           2.3, 1.1, 2.9, 3.8, 2.1, 0.8, 1.5, 1.0, 1.4, 2.1, 1.2, 2.5, 3.8, 1.8, 2.0,
           1.5, 1.7, 2.7, 2.0, 2.4, 3.0, 4.6, 4.3, 2.1, 1.3, 1.6, 2.0, 1.2, 0.8, 2.8)
m <- mean(times)
s2 <- var(times)
round(c(n = length(times), mean = m, variance = s2), 3)
# Set the gamma's mean and variance equal to the data's and solve
beta_g <- m / s2
alpha_g <- m^2 / s2
round(c(alpha = alpha_g, beta = beta_g), 2)
# Going over 3 minutes: in the data, under the gamma and under the line t/8
round(c(data = mean(times > 3), gamma = 1 - pgamma(3, alpha_g, beta_g), line = 1 - 9 / 16), 3)
# The quartiles of the data and of each model
round(rbind(data = quantile(times, c(0.25, 0.5, 0.75)),
            gamma = qgamma(c(0.25, 0.5, 0.75), alpha_g, beta_g),
            line = 4 * sqrt(c(0.25, 0.5, 0.75))), 2)
# Histogram with both densities
hist(times, breaks = seq(0.5, 5, by = 0.5), freq = FALSE, ylim = c(0, 0.6),
     main = "Heating time", xlab = "minutes", ylab = "density")
curve(dgamma(x, alpha_g, beta_g), add = TRUE, lwd = 2, col = "red")
curve(ifelse(x > 0 & x < 4, x / 8, 0), add = TRUE, lwd = 2, lty = 2)

Output

       n     mean variance 
  60.000    2.175    0.859 
alpha  beta 
 5.51  2.53 
 data gamma  line 
0.150 0.175 0.438 
      25%  50%  75%
data  1.4 2.10 2.80
gamma 1.5 2.04 2.71
line  2.0 2.83 3.46
Sixty heating times and two modelsDensity-scale histogram of 60 times with half-minute bars between 0.5 and 5: heights 0.23, 0.40, 0.33, 0.40, 0.33, 0.10, 0.13, 0.03 and 0.03. The red curve of the gamma 5.51 2.53 follows the outline, peaking near 2; the dashed line t over 8 rises up to 4, where there is hardly any data left.0.00.20.40.6012345minutesdensitygamma(5.51, 2.53)line t/8 (theory)
Redrawn with the site colours: the fitted gamma follows the data; the line from the theory puts probability where hardly anyone is.

The 60 times have mean 2.175 minutes and variance 0.859. The matching gamma is gamma(5.51,2.53)\text{gamma}(5.51, 2.53). With it, the probability of going over 3 minutes is 0.175, and in the data it is 0.150 (9 out of 60); the line said 0.438, almost three times as much. The quartiles tell the same story: those of the gamma (1.50, 2.04 and 2.71) are less than a tenth away from those of the data (1.40, 2.10 and 2.80), and those of the line (2.00, 2.83 and 3.46) overshoot by far. In the drawing, the red gamma curve follows the outline of the bars: it rises to a peak between 1.5 and 2.5 and falls; the dashed line keeps rising just where the data run out.

How to read it

  • The first line summarises the sample: 60 times, mean 2.175 and variance 0.859 (with var, which divides by n−1n – 1, as in topic 1).
  • alpha and beta: β=2.175/0.859=2.53\beta = 2.175/0.859 = 2.53 and α=2.1752/0.859=5.51\alpha = 2.175^2/0.859 = 5.51. They do not have to be whole numbers: α=5.51\alpha = 5.51 is no longer read as “5.51 steps”, just as a shape. The mean of the fitted gamma is 5.51/2.53=2.185.51/2.53 = 2.18, the data’s, by construction.
  • The row of probabilities is the decisive comparison: the gamma is off by 0.025; the line, by 0.29.
  • The quartile table comes from rbind, which stacks three vectors one on top of another with the name of each row. Reading it by columns means comparing the three models on the same quartile.
  • The plot: the data have a right tail (a few times of 4 minutes or more) and a peak left of center, the typical shape of a gamma. The toy model’s line puts its maximum at the right end: exactly the opposite.

The line t/8, from the density to the output

In the code, the line shows up as 1 - 9 / 16 and as 4 * sqrt(...). Both come from its distribution function: integrating t/8 t/8 from 0, F(t)=t2/16 F(t) = t^2/16 between 0 and 4.

  • Going over 3 minutes. P(T>3)=1−F(3)=1−9/16=0.4375 P(T > 3) = 1 – F(3) = 1 – 9/16 = 0.4375 , which with three decimals is the 0.438.
  • The quartiles. The p p quartile is the t t with t2/16=p t^2/16 = p , that is, t=4p t = 4\sqrt{p} : 4⋅0.5=2 4 \cdot 0.5 = 2 , 4⋅0.7071=2.83 4 \cdot 0.7071 = 2.83 and 4⋅0.8660=3.46 4 \cdot 0.8660 = 3.46 .

According to the line, half the times would be over 2.83 minutes. In the data, only 14 out of 60 are.

Check you’ve got it: according to the line, what is the probability of going over 4 minutes? And what do the data say?

The line gives 0: its density is 0 from 4 onwards, because F(4)=16/16=1 F(4) = 16/16 = 1 . In the data there are two times above it, 4.3 and 4.6. A model that says “impossible” to something you have seen twice in one lunchtime does not describe the cafeteria. The gamma, which has no ceiling, leaves room for them.

Questions you might ask

So was the theory wrong? The t/8t/8 model was useful for learning how to integrate a density, not for describing the cafeteria. What you learn here is the opposite: before using a model, you check whether the data look like it. A model is good or bad for some data.

Why match the mean and variance and not something else? Because the gamma has two parameters and you need two equations. The easiest are those of the mean and the variance, which have closed formulas. It is exactly what the exam asks when it says “set the model’s mean and variance equal to the sample’s and solve”. There are other methods (maximum likelihood, topic 9) that give somewhat different values.

Can I trust 60 data points? To choose between a gamma and a line, yes: the difference is huge. To tell a gamma(5.5, 2.5) from a gamma(6, 2.8) you would need much more data. The sample quartiles have their own error, like the simulated mean in program 1.

What does lty = 2 do? It draws a dashed line (line type 2). It lets you tell two curves apart without relying on colour, which gets lost in a photocopy of the exam.

Solving the wrong way round: α=m/s2\alpha = m/s^2 and β=m2/s2\beta = m^2/s^2. Always check that α/β\alpha/\beta gives the data’s mean. With the parameters swapped, the gamma’s mean would be 2.53/5.51=0.462.53/5.51 = 0.46 minutes.

What would happen if you computed the variance dividing by n instead of n − 1?

var divides by n−1 n – 1 , but in other books the method of moments uses the variance that divides by n n . How much does it move the fit? Run it after program 3:

# Run after program 3: it uses its times vector
m <- mean(times)
s2_n1 <- var(times)                 # divides by n - 1 = 59 (what var does)
s2_n <- mean((times - m)^2)         # divides by n = 60
round(c(n_minus_1 = s2_n1, n = s2_n), 3)
fit <- function(s2) c(alpha = m^2 / s2, beta = m / s2)    # the two formulas from program 3
round(rbind(n_minus_1 = fit(s2_n1), n = fit(s2_n)), 2)
# What decides whether the model is good: going over 3 minutes and the quartiles
p <- fit(s2_n)
round(c(over_3 = 1 - pgamma(3, p[1], p[2])), 3)
round(qgamma(c(0.25, 0.5, 0.75), p[1], p[2]), 2)

Output:

n_minus_1         n 
    0.859     0.844 
          alpha beta
n_minus_1  5.51 2.53
n          5.60 2.58
over_3 
 0.173 
[1] 1.51 2.05 2.71

The variance drops from 0.859 to 0.844 (multiplying by 59/60). Since α \alpha and β \beta have s2 s^2 in the denominator, both go up by 1.7%: 5.60 and 2.58. The model’s mean is still 2.175, and what tells you whether it fits barely moves: going over 3 minutes drops from 0.175 to 0.173 and the quartiles stay within one hundredth. Use the variance the question asks for, but what separates a good model from a bad one is the shape, as with the line.

Try it yourself

  • Also fit a uniform between the minimum and the maximum of the data (min(times) and max(times)) and add its probability of going over 3 minutes to the comparison. Is it closer than the line?
  • Add five times of 6 minutes to the vector (someone heating a frozen lasagne) and repeat the fit: how much do α\alpha and β\beta change? And the data’s quartiles?

Common mistakes in this practice

  • Rate for scale in rgamma, pgamma and pexp. The unnamed number is the rate. If you are given the mean of each step, name scale or pass its inverse.
  • A count histogram with a density on top. Use freq = FALSE when you are going to draw a theoretical curve.
  • Believing the simulation without the theory next to it. Every simulated number is compared with its theoretical value. If they do not look alike, the mistake is usually in a parameter.
  • Multiplying instead of adding independent variables. 3 * rexp(n, 0.5) is not the sum of three waits: it has the same mean and three times the variance.
  • Forgetting set.seed. Without a seed, each run gives different numbers and you cannot compare your output with the article’s or repeat a result.
  • Judging the fit only by the mean. The mean of the fitted gamma matches the data’s by construction: what tells you whether the model is good are the probabilities, the quartiles and the plot.

Try it in the R playground

Open the site’s R playground (or RStudio) and paste this script, which brings together the essentials of the three programs on a small scale:

set.seed(2026)
t <- rexp(2000, 0.5)                            # arrivals in the queue
c(mean(t), 1 / 0.5)
hist(t, breaks = 30, freq = FALSE, main = "Arrivals", xlab = "minutes")
curve(dexp(x, 0.5), add = TRUE, lwd = 2, col = "red")
w <- rexp(2000, 0.5) + rexp(2000, 0.5) + rexp(2000, 0.5)   # three people ahead
c(mean(w <= 5), pgamma(5, 3, 0.5))
hist(w, breaks = 30, freq = FALSE, main = "Three ahead", xlab = "minutes")
curve(dgamma(x, shape = 3, rate = 0.5), add = TRUE, lwd = 2, col = "red")

What to look at:

  • In the Environment panel, t and w appear as numeric vectors of 2,000 values: click on them (or type View(t)) to see the times one by one.
  • In the first histogram, the red curve almost touches the bars. Change the 0.5 in curve to 2 (without touching the data) and you will see what happens when the model has the wrong parameter.
  • Change breaks = 30 to breaks = 100: the bars get thinner and more irregular, because each one has less data. It is the histogram from the theory, but with little data.
  • Type ?curve and look at the add argument: without it, curve wipes the histogram and draws the curve alone.

Summary

  • A simulation is always read next to its theoretical value: mean, variance, probabilities and quantiles. Differences of a few thousandths are noise; big ones, a misplaced parameter.
  • mean(condition) is a relative frequency and gets close to the probability when there is a lot of data.
  • Memorylessness is checked by filtering: of those who have already waited ss, the proportion that waits tt more is that of waiting tt from the start.
  • The sum of α\alpha independent exponentials is a gamma; adding is not multiplying.
  • In R, the unnamed number in pgamma and pexp is the rate. Naming scale or rate avoids the mistake from the opening.
  • To fit a gamma to data, β=m/s2\beta = m/s^2 and α=m2/s2\alpha = m^2/s^2, and the model is judged with probabilities, quartiles and the histogram.

Checklist: have you practised it?

  • Have you run the three programs and checked the outputs against these?
  • Can you explain why mean(t < 1) is an approximate probability?
  • Could you check the exponential’s memorylessness with simulated data?
  • Do you know why rgamma(n, 3, 2) is not “three steps of 2 minutes”?
  • Could you fit a gamma to a sample by matching mean and variance?
  • Have you tried the “Try it yourself” tasks without looking at the theory?

If you answered yes to almost everything, you are ready for the continuous random variables exercises, where I no longer give you the code and the parts carry exam marks. See you there!

Next step: exercisesContinuous random variables — exam-style exercises with the cafeteria microwave, a density with a constant and three ways to pay (and the uniroot that could not find the median)

Did this article help you? Here is how you can support SergioLearns →