Inequalities and limit theorems in R — practice with 100,000 songs, running means, replicate and qqnorm (and the histogram that was a single bar)
My first attempt at the CLT practical was a histogram with one single, very tall bar. I had written sample_songs <- 2 + rexp(25, 2/3) on one line and, on the next, replicate(10000, mean(sample_songs)). R obeyed: it computed the mean of the same sample ten thousand times, and all ten thousand came out equal. replicate repeats an expression, but if the sample was already made outside, it does not draw it again. The fix is to put the simulation inside a function, as practical 9 of the course does, and it is the first thing you will see in program 3.
This is the R practice for inequalities and limit theorems: three programs that check with simulations what the theory and the proofs do on paper. The first one sets the Markov and Chebyshev bounds against 100,000 songs; the second shows the law of large numbers with four playlists and with the probability of moving away from the mean; the third repeats the CLT of practical 9 with histograms and qqnorm, and uses it for the 20-song session and the skipped songs. Every output, explained number by number.
Table of Contents
Before we start
- The three programs can be pasted as they are into the site’s R playground or into RStudio. They only use base R: nothing to install.
- The simulations use
set.seed(2026): if you copy it the same, you get the same numbers as here. - The example is the one of the whole topic: the length of a song on the gym playlist, with , with mean minutes and standard deviation . A song is simulated with
2 + rexp(1, 2/3). - Calculations with 2 decimals, as in the exam (
round(x, 2)); small probabilities, with 3 or 4.
Program 1: the bounds against 100,000 songs
The idea
Markov and Chebyshev give bounds that hold for any variable. With 100,000 simulated songs we compute the real frequency and compare it with the bound and with the exact value (which we know here, because is an exponential):
- Markov: , for .
- Chebyshev: , for , and a drawing of the bound against the frequency for from 1 to 4.
In words: a bound is a promise that holds for any playlist in the world, and that is why it is so cautious. Markov only uses the mean: if the average song lasts 3.5 minutes, there cannot be many lasting 7 or more, because they would push the mean up. Chebyshev also uses the standard deviation, so it knows a bit more and usually gets closer. Neither of them knows that our song is 2 fixed minutes plus an exponential. That is why the program has three columns: what the bound promises, what happens in 100,000 songs and what the exact calculation gives, . If the simulation and the exact value agree, the simulation is right; the gap between them and the bound is what it “costs” not to know the distribution.
The code
set.seed(2026)
x <- 2 + rexp(100000, 2/3) # 100,000 songs
# 1. Markov: P(X >= t) <= E(X) / t
t <- c(5, 7, 9)
markov <- data.frame(t, bound = 3.5 / t,
simulated = sapply(t, function(s) mean(x >= s)),
exact = 1 - pexp(t - 2, 2/3)) # X - 2 is an exp(2/3)
round(markov, 4)
# 2. Chebyshev: P(|X - mu| >= k sigma) <= 1 / k^2
k <- c(1.5, 2, 3)
cheb <- data.frame(k, bound = 1 / k^2,
simulated = sapply(k, function(j) mean(abs(x - 3.5) >= 1.5 * j)),
exact = 1 - pexp(1.5 + 1.5 * k, 2/3)) # only the upper tail
round(cheb, 4)
# 3. The bound and the frequency for k from 1 to 4, in a drawing
kk <- seq(1, 4, by = 0.25)
sim <- sapply(kk, function(j) mean(abs(x - 3.5) >= 1.5 * j))
plot(kk, 1 / kk^2, type = "l", lwd = 2, ylim = c(0, 1), xlab = "k", ylab = "probability")
points(kk, sim, pch = 19, col = "red")
Output
t bound simulated exact
1 5 0.7000 0.1351 0.1353
2 7 0.5000 0.0354 0.0357
3 9 0.3889 0.0097 0.0094
k bound simulated exact
1 1.5 0.4444 0.0814 0.0821
2 2.0 0.2500 0.0492 0.0498
3 3.0 0.1111 0.0184 0.0183
How to read it
- Markov table, row
t = 7: the bound says at most half of the songs last 7 minutes or more (bound 0.5000). The simulated ones are 3.54 % (simulated 0.0354) and the exact one 3.57 %. Simulation and exact almost coincide: the bound is fourteen times higher. - Markov table,
boundcolumn: it goes down like (0.70, 0.50, 0.39). The real probability goes down much faster (0.135, 0.035, 0.009), like an exponential. The further out, the looser Markov is. - Chebyshev table, row
k = 2: the bound allows 25 % outside ; there is 4.92 % simulated and 4.98 % exact. Withk = 3, 11.1 % allowed and 1.8 % really. - The drawing: the black line is the bound and the red dots the simulated frequency. All the dots stay below the line, as they must, and further and further below. At the bound is 1 (it says nothing) and the frequency is 0.135.
The t = 7 row and the k = 2 row, by hand
The two most discussed rows of the output can be done on paper. Like this:
| Quantity | Calculation | Result | Why |
|---|---|---|---|
| Markov bound, | 0.50 | : only the mean is needed | |
| Exact, | 0.0357 | lasting 7 or more means the exponential part goes past 5, because the first 2 minutes are fixed | |
| Chebyshev interval, | from 0.5 to 6.5 | : outside it is “far” | |
| Lower tail | 0 | no song lasts less than 2 minutes | |
| Upper tail | 0.0498 | the same calculation as in Markov, with | |
| Chebyshev bound | 0.25 | : it does not depend on the distribution |
Notice that the exact value for is just the upper tail: that is why in the code exact is 1 - pexp(1.5 + 1.5 * k, 2/3). The is : the upper end of the interval minus the 2 fixed minutes.
Check you’ve got it: where does the 0.0183 in the k = 3 row come from?
With the interval is , from −1 to 8. Below there is nothing (a song cannot last less than 0 minutes, let alone −1). Above, . The bound allows 0.1111, six times more.
Questions you may ask yourself
- Why does
mean(x >= s)give a probability? Becausex >= sis a vector ofTRUEandFALSE, andmeanturns it into ones and zeros: the mean is the proportion ofTRUE. It is the law of large numbers in one line. - Why is there only one tail in Chebyshev’s
exact? Because no song lasts less than 2 minutes and is below 2 for : the lower tail is 0. - What is
sapplyfor? To apply the same calculation to eacht(or eachk) and return a vector. Without it,mean(x >= t)would comparexwith the vectortby recycling it, and would give a meaningless number.
Writing mean(abs(x - 3.5) >= 1.5 * k) with the whole vector k. R does not warn: it recycles 1.5 * k along the 100,000 values (each song against a different ) and gives a single mixed proportion. With several values, sapply.
Try it yourself
- Change the playlist to a normal,
x <- rnorm(100000, 3.5, 1.5), and repeat the Chebyshev table. With you should get close to 0.0455. - Find a variable that comes close to the bound:
x <- sample(c(0.5, 3.5, 6.5), 100000, replace = TRUE, prob = c(1/8, 3/4, 1/8))has mean 3.5 and standard deviation 1.5. What ismean(abs(x - 3.5) >= 3)?
Program 2: the law of large numbers, at work
The idea
Two ways of seeing that approaches :
- One long playlist: the mean of the first songs, for . Four different playlists, four paths that end in the same place.
- Many playlists of songs: what proportion has a mean 0.25 minutes or more away from 3.5, for , against the law of large numbers bound, .
In words, the two parts look at the same law from two places. In the first one you listen to a playlist song by song and, after each one, you recompute the mean of everything so far: at the start a long song moves it a lot, and at the end hardly at all, because it is shared among hundreds. In the second one you do not follow anyone: you prepare a thousand playlists of songs, count how many have a “bad” mean (0.25 minutes or more away from 3.5) and watch how that proportion falls as grows. The first is the strong law; the second, the weak one.
The code
set.seed(2026)
# 1. Four playlists of 1000 songs: the running mean of each one
paths <- replicate(4, { y <- 2 + rexp(1000, 2/3); cumsum(y) / (1:1000) })
round(paths[c(10, 100, 1000), ], 3) # means after 10, 100 and 1000 songs
matplot(paths, type = "l", lty = 1, log = "x", xlab = "n", ylab = "mean")
abline(h = 3.5, lty = 2)
# 2. Probability that the mean moves 0.25 or more away, against the bound
set.seed(2026)
outside <- function(n, m = 1000) mean(replicate(m, abs(mean(2 + rexp(n, 2/3)) - 3.5) >= 0.25))
n <- c(25, 50, 100, 200, 400)
round(data.frame(n, simulated = sapply(n, outside),
bound = pmin(1, 2.25 / (n * 0.25^2))), 3)
Output
[,1] [,2] [,3] [,4]
[1,] 4.073 4.788 3.140 3.839
[2,] 3.695 3.624 3.430 3.510
[3,] 3.561 3.532 3.577 3.577
n simulated bound
1 25 0.394 1.00
2 50 0.242 0.72
3 100 0.116 0.36
4 200 0.013 0.18
5 400 0.001 0.09
How to read it
- The 3 × 4 matrix: each column is a playlist and each row a moment. After 10 songs the means range from 3.14 to 4.79: they are all over the place. After 100, from 3.43 to 3.70. After 1000, from 3.53 to 3.58: all four close to 3.5.
- The drawing: the four lines start from very different places (the second playlist starts with several remixes and climbs almost to 5) and come together on the dashed 3.5.
matplotdraws each column of the matrix as a line. - The table,
simulatedcolumn: with 25 songs, 39.4 % of the playlists have a mean a quarter of a minute or more away from 3.5; with 100, 11.6 %; with 400, 0.1 %. It is the probability the law of large numbers sends to 0. - The table,
boundcolumn: , capped at 1 withpmin(with it would be 1.44, and a probability does not exceed 1). The simulated one is always below: with , 0.013 against 0.18.
The first playlist, song by song
The line cumsum(y) / (1:1000) makes a thousand means in one go. These are the first ten of the first playlist (with the same set.seed(2026), 2 decimals):
| Song (min) | Running sum | Mean of the first | Why | |
|---|---|---|---|---|
| 1 | 2.60 | 2.60 | 2.60 | with one song, the mean is that song |
| 2 | 2.17 | 4.77 | 2.38 | another short one: the mean goes down |
| 3 | 4.26 | 9.03 | 3.01 | a long one pushes the mean up by more than half a minute |
| 4 | 3.25 | 12.28 | 3.07 | close to 3.5: the mean barely moves |
| 5 | 2.17 | 14.45 | 2.89 | short again |
| 6 | 8.11 | 22.56 | 3.76 | a remix: almost a minute in one go |
| 7 | 3.30 | 25.86 | 3.69 | |
| 8 | 2.24 | 28.10 | 3.51 | right at 3.5, by chance |
| 9 | 10.06 | 38.16 | 4.24 | the 10-minute song drags the mean up |
| 10 | 2.58 | 40.73 | 4.07 | the 4.073 in the first column of the output |
Each row is the previous sum plus the new song, divided by . Song 9 raises the mean by 0.73 minutes because it is only shared among 9; the same song in position 900 would raise it by less than a hundredth. That is the law of large numbers: each new song weighs .
Check you’ve got it: with which n does the bound in the table drop below 5 %?
The bound is . For it to be 0.05 or less, songs. The simulated value is already below 5 % with (0.013): the bound asks for more than three times as many songs as needed, because it holds for any variable with that mean and that variance.
Questions you may ask yourself
- What do the braces
{ … }insidereplicatedo? They group several instructions into a single expression. Each repetition makes a new playlistyand returns its running mean (the last line of the block).replicateputs each result in a column. - Why
log = "x"? Because the interesting part happens at the beginning: with a normal axis, the first 10 songs would take up 1 % of the drawing. On a log scale, 1 to 10 takes up as much as 100 to 1000. - Why the second
set.seed(2026)? So the table comes out the same even if you change part 1. Eachset.seedrestarts the random numbers.
The bound in the table is the one of the weak law, which talks about different playlists for each . The four lines in the drawing are the strong law: one and the same playlist whose mean ends up still at 3.5.
Try it yourself
- Repeat the table with
c0 <- 0.5instead of 0.25. With which does the simulated one drop below 5 %? And the bound? - Change the playlist to proportions of skipped songs:
y <- rbinom(1000, 1, 0.25). The running means should go to 0.25.
Program 3: the CLT with histograms and qqnorm
The idea
It is the exercise of practical 9 with the playlist. We simulate 10,000 means of songs for and and check in three ways that they approach an :
- their mean and standard deviation against the theoretical ones;
- their histogram with the normal density on top;
- the quantile-quantile plot (
qqnorm) of the standardised means.
Then we use the CLT for three probabilities and compare them with the simulation and with the exact value.
In words, the three probabilities are the same recipe with three different variables. First you decide what is “normal”: the mean of 50 songs, the sum of 20 or the number of skipped songs out of 40. Then, its mean and standard deviation ( and ; and ; and ). And finally, pnorm with those two numbers. The simulation tells you what really happens and the exact value (gamma or binomial) confirms it; the CLT column tells you how wrong the approximation is.
The code
set.seed(2026)
song_mean <- function(n) mean(2 + rexp(n, 2/3)) # the mean of n NEW songs each time
m <- 10000
means5 <- replicate(m, song_mean(5))
means50 <- replicate(m, song_mean(50))
round(c(mean = mean(means5), sd = sd(means5), theoretical = 1.5 / sqrt(5)), 3)
round(c(mean = mean(means50), sd = sd(means50), theoretical = 1.5 / sqrt(50)), 3)
# Histograms with the CLT normal
par(mfrow = c(1, 2))
hist(means5, freq = FALSE, breaks = 40, main = "n = 5", xlab = "mean")
curve(dnorm(x, 3.5, 1.5 / sqrt(5)), add = TRUE, col = "red", lwd = 2)
hist(means50, freq = FALSE, breaks = 40, main = "n = 50", xlab = "mean")
curve(dnorm(x, 3.5, 1.5 / sqrt(50)), add = TRUE, col = "red", lwd = 2)
# Quantile-quantile plots of the standardised means
qqnorm((means5 - mean(means5)) / sd(means5), main = "n = 5"); abline(0, 1, col = "red")
qqnorm((means50 - mean(means50)) / sd(means50), main = "n = 50"); abline(0, 1, col = "red")
# Three probabilities: simulated, CLT and exact
round(c(simulated = mean(means50 > 3.8), CLT = 1 - pnorm(3.8, 3.5, 1.5 / sqrt(50)),
exact = 1 - pgamma(50 * (3.8 - 2), 50, 2/3)), 4)
sessions <- replicate(m, sum(2 + rexp(20, 2/3))) # 10,000 sessions of 20 songs
round(c(simulated = mean(sessions <= 75), CLT = pnorm(75, 70, 1.5 * sqrt(20)),
exact = pgamma(35, 20, 2/3)), 4)
skips <- rbinom(m, 40, 0.25) # songs skipped out of 40
round(c(simulated = mean(skips <= 8), exact = pbinom(8, 40, 0.25),
without = pnorm(8, 10, sqrt(7.5)), with = pnorm(8.5, 10, sqrt(7.5))), 4)
Output
mean sd theoretical
3.501 0.675 0.671
mean sd theoretical
3.497 0.213 0.212
simulated CLT exact
0.0842 0.0786 0.0844
simulated CLT exact
0.7851 0.7720 0.7827
simulated exact without with
0.2994 0.2998 0.2326 0.2919
How to read it
mean 3.501and3.497: the means of the means are at 3.5 with 5 and with 50 songs. does not depend on .sd 0.675againsttheoretical 0.671, and0.213against0.212: the simulated standard deviation is the theoretical one, . With 50 songs the mean is times more precise than with 5.- The histograms: with the normal almost fits, but the histogram has its peak a little to the left of the curve and a longer right tail: the skewness of each song still shows. With histogram and curve are the same shape.
- The quantile-quantile plots: each point compares a quantile of the standardised means with the same quantile of the ; if the distribution were normal, they would fall on the red line. With the points curve upwards at both ends: the left tail is shorter and the right one longer than those of the normal (right skew). With the points stick to the line except at the right tip.
simulated 0.0842,CLT 0.0786,exact 0.0844: probability that the mean of 50 songs exceeds 3.8 minutes. The CLT is off by six thousandths: in far tails is where the remaining skewness shows most (it is the right tip of the quantile-quantile plot).0.7851,0.7720,0.7827: the 20-song session from the theory. The simulation gives the exact value and the CLT stays one hundredth below.0.2994,0.2998,0.2326,0.2919: the skipped songs. Simulated and exact coincide; without correction, the normal goes to 0.23; with the continuity correction, to 0.29.
The three CLT probabilities, standardised
pnorm(3.8, 3.5, 1.5 / sqrt(50)) does the standardisation inside. In the exam, with tables, it goes like this:
| Question | CLT normal | Standardise | Probability | Why |
|---|---|---|---|---|
| , | the mean has standard deviation , not 1.5 | |||
| the sum has mean and standard deviation | ||||
| Skipped , uncorrected | binomial : mean , variance | |||
| Skipped , corrected | “8 or fewer” in whole numbers reaches 8.5 on the line: the bar for 8 goes from 7.5 to 8.5 |
With rounded to 2 decimals, as in the normal table, you get 0.0793, 0.7734 and 0.2912: the third digit changes, and that is why in the exam you write down the you used. The second row is the one most often confused: the sum is standardised with and the mean with .
The hook’s one: making the sample outside replicate. If you write sample_songs <- 2 + rexp(5, 2/3) and then replicate(m, mean(sample_songs)), you get the same number 10,000 times and the histogram is one bar. What is repeated has to generate the data: that is why song_mean(n) calls rexp inside.
What would happen if a session were the same song repeated 20 times?
The hook’s mistake has a cousin: the 20 songs of the session not being independent. If you put one song on repeat, the session lasts , not . The mean is still 70 minutes, but nothing else looks the same:
set.seed(2026)
m <- 10000
# Normal sessions: 20 different songs, independent of each other
indep <- replicate(m, sum(2 + rexp(20, 2/3)))
# Looped sessions: ONE song repeated 20 times (the sum is 20 times the same X)
loop <- replicate(m, 20 * (2 + rexp(1, 2/3)))
round(rbind(indep = c(mean = mean(indep), sd = sd(indep), P75 = mean(indep <= 75)),
loop = c(mean = mean(loop), sd = sd(loop), P75 = mean(loop <= 75))), 2)
Output:
mean sd P75 indep 69.99 6.75 0.78 loop 69.82 29.52 0.69
The standard deviation goes from about 6.7 minutes to about 30: against . With independent songs, long and short ones balance out within the session; with a single repeated song there is nothing to balance. And the shape does not become normal: , the same old exponential. If you applied the CLT you would get 0.77, and with a normal of standard deviation 30, 0.57: both wrong. The CLT needs many independent variables added up; repeating the same one does not count.
Questions you may ask yourself
- Why standardise before
qqnorm? To be able to draw the line withabline(0, 1)and compare both on the same scale. Without standardising you useqqline(means5), which draws the line through the quartiles. - Why
50 * (3.8 - 2)in the exact one? Because is the same as , and (one hundred = 50 songs × 2 fixed minutes) is a gamma(50, 2/3): . - How many means to simulate? With
m = 10000the proportions have an error of a few thousandths (): enough to see the shape and compare with the CLT.
Try it yourself
- Do the same with and (practical 9 uses 25, 100 and 500). With which does the curve stop showing in the quantile-quantile plot?
- Change the song to a uniform,
song_mean <- function(n) mean(runif(n, 2, 5)), with and . With the quantile-quantile plot is already almost a line: the uniform is symmetric. - With the Bernoulli variables of practical 9:
song_mean <- function(n) mean(rbinom(n, 1, 0.25)). With the histogram comes out in steps: the mean only takes the values 0, 0.1, 0.2…
Typical mistakes in this practice
hist(means) without freq = FALSE and then curve(dnorm(...), add = TRUE). The histogram comes out in frequencies (hundreds) and the density (less than 1) is stuck to the floor. To compare with a density, always freq = FALSE.
Using sd = 1.5 in the curve of the means. The normal of has standard deviation : with sd = 1.5 the curve is five times wider than the histogram with and it looks as if the CLT fails.
Accepting the normal by looking only at the histogram. The histogram “looks like” a bell; the quantile-quantile plot shows the skewness that remains. That is why practical 9 asks for both.
Forgetting set.seed and comparing your numbers with a classmate’s. Without a seed, each run gives different songs: the results are similar, but not equal.
Try it in the R playground
Open the R playground on the site (or RStudio) and paste this script. It is program 3 in small, to play with :
set.seed(2026)
n <- 10 # change n: 1, 2, 5, 10, 30, 100
means <- replicate(10000, mean(2 + rexp(n, 2/3)))
par(mfrow = c(1, 2))
hist(means, freq = FALSE, breaks = 40, main = paste("n =", n))
curve(dnorm(x, 3.5, 1.5 / sqrt(n)), add = TRUE, col = "red", lwd = 2)
qqnorm(means); qqline(means, col = "red")
c(sd_simulated = sd(means), sd_theoretical = 1.5 / sqrt(n))
Things to look at:
- That with
n <- 1the histogram is the song itself and the quantile-quantile plot, a very marked curve. - That as
ngrows the histogram narrows (the standard deviation goes down like ) and becomes symmetric. - That the points of the quantile-quantile plot straighten first in the center and last at the right tip.
- That
sd_simulatedandsd_theoreticalcoincide for anyn: that is not the CLT, it is the variance of a mean, which always holds.
Summary
- A simulated probability is
mean(condition)over many repetitions; for several values,sapply. - The Markov and Chebyshev bounds always stay above the simulated frequency, and more so the further out.
cumsum(x) / seq_along(x)gives the running means (strong law);replicatewith the simulation inside gives many means of (weak law and CLT).- The CLT is checked with three things: mean , standard deviation and normal shape (histogram with
freq = FALSEandqqnorm). - The CLT fails more in far tails and with small ; for integer variables, the continuity correction almost fixes it.
Checklist: have you practised it?
- [ ] I can compare a bound with the simulated frequency and with the exact one.
- [ ] I can draw running means with
log = "x"and explain what they show. - [ ] I can simulate 10,000 means with
replicateand a function that generates the data inside. - [ ] I can draw a histogram with the CLT normal on top and read a
qqnorm. - [ ] I can compute a probability of a sum or a mean with the CLT and compare it with the simulation.
With this, on to the inequalities and limit theorems exam-style exercises, where the CLT appears as in EC2: first the mean and variance of a density, then pnorm.
Did this article help you? Here is how you can support SergioLearns →



