Stage I · Bachelor's: Foundations
Part 7 of 65Randomness on Demand
How does a deterministic machine make randomness, and how do you run an honest simulation?
Von Neumann warned in 1951 that arithmetic randomness is a state of sin, and IBM's RANDU proved him right: turn its consecutive triples in a cube and every point falls on one of fifteen planes. The part builds a generator (Lehmer's congruences, then PCG32) and the tests that catch a bad one, then shapes uniforms into any law by the inverse CDF, rejection, Box-Muller, Marsaglia-Tsang and Walker's alias table. Monte Carlo integration has error sigma over root n in any dimension, from Buffon's needle to Lazzarini's suspicious 355/113. The part turns from making randomness to using it honestly: a simulation study is an experiment with a protocol (ADEMP), seeds, streams and a Monte Carlo standard error on every number, and the textbook interval for a proportion fails it. It ends with Markov chains: Markov's count of vowels in Onegin, stationary laws and PageRank, the riffle shuffle's cutoff near seven, and the Metropolis algorithm on a two-humped target.
What you need. Modular arithmetic and a little programming; the CDFs and densities of Part 3 and the laws of large numbers of Part 6. Chapters 8 to 10 use matrix multiplication and eigenvectors.
- Hook
- von Neumann's "state of sin", 1951
- Mathematics
- PRNGs and RANDU, samplers, Monte Carlo error, simulation-study design, Markov chains, Metropolis
- Built
- statkit.random; the simulation-study harness
What you will be able to do
Bachelor's
- Compute the period of a small congruential generator by hand, and explain why passing a one-dimensional test did not save RANDU.
- Derive an inverse-CDF sampler for the exponential, Pareto or logistic law, and the acceptance rate 1/M of a rejection sampler.
Master's
- Prove that rejection sampling and Box-Muller give the laws they claim, and that a chain in detailed balance with a law has it as a stationary law.
- Compute the variance saved by antithetic pairs, a control variate and importance sampling on a stated integral.
PhD
- Compute the total-variation distance of k riffle shuffles from uniform by the Bayer-Diaconis formula, and state what the cutoff phenomenon claims about how the distance falls.
Practice
- Plan and report a simulation study by ADEMP: one recorded seed, a stream per scenario, the same data sets for every method, and a Monte Carlo standard error beside every number.
- Choose the number of replicates needed to resolve a stated difference in coverage.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 26 min · Master's 47 min · PhD 51 min · Practice 30 min.
- 0A state of sinBachelor's3 min
- 1Pseudo-random generatorsBachelor's5 min
- 2The inverse CDFBachelor's4 min
- 3Rejection samplingBachelor's4 min
- 4Special methodsMaster's3 min
- 5Monte Carlo integrationBachelor's5 min
- 6Simulation studies done rightPractice4 min
- 7Variance reductionMaster's4 min
- 8Markov chainsBachelor's4 min
- 9Stationary distributionsMaster's4 min
- 10Mixing: seven shufflesPhD4 min
- 11The Metropolis algorithmMaster's5 min
- Recap, problems, and the road aheadAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film. A dashed box stands for a number the film computes when it is rendered (hover over it to see what is computed); the README's figures for each chapter, where it lists them, follow the chapter's text.
A state of sinBachelor's3 min
Every simulation in this series so far, millions of coin tosses, normals, Cauchys and Paretos, ran on a machine that can only follow instructions. Where did the randomness come from? In 1951 John von Neumann, who needed random numbers by the million to simulate neutrons for the hydrogen bomb, gave the answer that every generator since has had to live with. Anyone who considers arithmetical methods of producing random digits, he wrote, is, of course, in a state of sin. A deterministic generator with a fixed seed has a determined output. We use a sequence that behaves like random draws, while checking how it might fail.
Von Neumann's own method shows the danger. Take a four-digit number, square it, and keep the middle four digits of the eight-digit result: that's the next number. From twelve thirty-four you get fifty-two twenty-seven, then three two one five, and the digits look random enough. But from twenty-one hundred you get forty-one hundred, eighty-one hundred, sixty-one hundred, twenty-one hundred again: a cycle of length four. Other seeds decay to zero and stay there. Von Neumann knew this; he reportedly liked the method because it was fast, and because when it failed, it failed obviously. The dangerous failures are the ones you can't see.
In the 1960s IBM distributed a generator called RANDU with its System/360 computers. Multiply by sixty-five thousand five hundred and thirty-nine, and take the remainder after dividing by two to the thirty-one. Each number looks uniform, and passes simple tests. Now plot consecutive triples as points in a cube. From most angles: a uniform cloud. Turn it. Every point lies on one of just fifteen planes. Because sixty-five thousand five hundred and thirty-nine is two to the sixteen plus three, each number is six times the last minus nine times the one before, so nine x minus six y plus z is always an integer. George Marsaglia published the general result in 1968: random numbers fall mainly in the planes. RANDU stayed in wide use for years, in simulations nobody could easily recheck. A modern generator, PCG, shows no visible RANDU-style planes at this resolution; that picture is not proof of randomness.
What it does: Von Neumann (1951); his middle-square method and its cycles; RANDU's triples turned edge-on in 3D; PCG32's cube; the objectives.; Numbers (computed): 2100 → 4100 → 8100 → 6100 → 2100; 9x − 6y + z takes 15 integer values
1Pseudo-random generatorsBachelor's5 min
In 1949 Derrick Lehmer proposed the scheme that dominated for fifty years. Keep one integer. To get the next, multiply by a constant a, add c, and take the remainder after dividing by m. Divide by m and you have a number between zero and one. It's fast, it needs almost no memory, and it's reproducible: the same starting seed always gives the same sequence, which is exactly what a scientist wants when a simulation must be checked. But it can never produce more than m different numbers before repeating, and its structure is linear, which is what doomed RANDU.
Picture the m possible values as hours on a clock, here with sixty-four of them. With a equal to five and no increment, starting at one, the generator hops around the clock and returns to where it started after only sixteen steps: three quarters of the values are never visited. Add an increment of three, and the same multiplier now visits every one of the sixty-four values before repeating. When that happens was worked out by Thomas Hull and Alan Dobell in 1962: three conditions on a, c and m. Real generators use m equal to two to the thirty-two or two to the sixty-four, and choose a with care.
The linear structure is easiest to see in pairs. Plot each value against the next, for a small generator modulo two hundred and fifty-six. The points aren't scattered; they sit on a few parallel lines. It's true of every linear congruential generator: pairs fall on lines, triples on planes, and d-tuples on hyperplanes. The spectral test, from 1967, measures the widest gap between those hyperplanes; a good multiplier makes the gaps small in every dimension that matters. RANDU's multiplier made them enormous in three.
Modern generators keep the speed and hide the structure. Here is PCG32, designed by Melissa O'Neill in 2014, in four lines. Its state is a sixty-four-bit linear congruential generator, with a period of two to the sixty-four. But it never outputs the state directly. It mixes the high bits down with a shift and an exclusive or, then rotates the result by an amount chosen by the state's own top five bits. That data-dependent rotation conceals the simple state lattice in the output. And by changing the increment you get two to the sixty-three separate streams, but this does not guarantee independent or nonoverlapping output sequences. It's what we've built into statkit, and NumPy's default generator is its sixty-four-bit sibling.
You've almost certainly used another generator. In 1998 Makoto Matsumoto and Takuji Nishimura published the Mersenne Twister. Its period is two to the nineteen thousand nine hundred and thirty-seven, minus one, a number with six thousand digits, and its output is evenly spread in up to six hundred and twenty-three dimensions at thirty-two-bit accuracy. It became the default in Python, R and MATLAB. But it is linear in its bits, so it fails the tests in BigCrush that look for exactly that, and its large state recovers slowly from a seed with too many zeros. The lesson: an astronomically long period is necessary, but it is never enough.
How do you test a generator? With statistics. Split three hundred thousand numbers into ten bins and compare the counts with a chi-squared test: both generators pass, with large p-values. Count runs above and below the median: both look like independent draws. Now group the numbers into triples and count them in a thousand little cubes. PCG passes. RANDU fails with the tiny p-value shown: its triples occupy the cubes very unevenly, the cubes, because they live on fifteen planes. A test can only reject. Passing is evidence, never proof, so modern generators face batteries of over a hundred tests, like the BigCrush suite of Pierre L'Ecuyer and Richard Simard.
What it does: Lehmer's LCG (1949); periods on a 64-hour clock and Hull–Dobell; the lattice of pairs and the spectral test; PCG32 in four lines; the Mersenne Twister; χ², runs and 3-D tests.; Numbers (computed): period 16 vs 64; RANDU 1-D χ² p = 0.89 but 3-D p = 5 × 10⁻³⁰; PCG32 p = 0.87, 0.16
2The inverse CDFBachelor's4 min
With a good source of uniform numbers, how do we get any other distribution? The first answer is Part 3's probability integral transform, run backwards. Take a uniform U and apply the inverse of the CDF you want. The chance that the result is at most x is the chance that U is at most F of x, because F is nondecreasing and right-continuous. And for a uniform, that chance is just F of x. So X has CDF F, exactly. For CDFs with jumps or flat stretches, use the generalized inverse: the smallest x at which F reaches u. The proof is the same.
Here it is for the exponential distribution, whose CDF is one minus e to the minus x. Its inverse is minus the log of one minus u. Draw a uniform u and mark it on the vertical axis. Go across to the curve and down: that's the draw. Ten draws. Where the curve is steep, which is where the density is high, a band of u's maps to a narrow band of x's, so draws pile up there. Where it's flat, in the tail, the same band of u's spreads out across a wide range of x.
Four thousand draws this way, each using a single uniform from our PCG generator. The histogram approximates the exponential density; omitted tail draws stay in the denominator. One uniform in, one draw out: when the quantile is easy to evaluate, inversion is convenient. The same trick turns uniforms into Cauchys, with the tangent function; into Paretos, with a power; into Weibulls and logistics.
Inversion works for discrete laws too. Lay the probabilities end to end along the unit interval: a tenth for zero, a quarter for one, and so on. The cut points are the CDF. Draw a uniform and see which piece it lands in. Two thousand draws reproduce the probabilities. The only cost is the search for the right piece, which for a law with many values can take many steps. Chapter four's alias method removes it.
Inversion has one more use, and it's a famous one. Take a sample of five numbers and its empirical CDF from Part 1: a staircase climbing a fifth at each observation. Invert it. A uniform u lands on one step, and so picks one observation, each with chance one fifth. Five uniforms give five picks, with repeats: a sample drawn from the data with replacement. That's a resample, and simulating many of them is Bradley Efron's bootstrap of 1979, which Part 16 builds into a way of computing standard errors under appropriate regularity conditions.
Inversion has one requirement: an inverse CDF you can compute. The normal's inverse CDF has no elementary formula. It can be computed to sixteen digits, with a rational approximation like Michael Wichura's algorithm of 1988, but every draw then costs a careful numerical evaluation. Gamma and beta CDFs use special functions in general; their quantiles usually need numerical inversion. Alternative samplers can avoid numerical inversion. The next two chapters build them.
What it does: Proof; the exponential by −log(1 − U); 4,000 draws; discrete inversion; inverting the ECDF is resampling (the bootstrap); the normal's numerical quantile.; Numbers (computed): frequencies 0.10, 0.23, 0.30, 0.21, 0.15 vs 0.10, 0.25, 0.30, 0.20, 0.15
3Rejection samplingBachelor's4 min
Von Neumann's second idea, from the same 1951 paper, needs no inverse at all. Suppose we want draws from the beta distribution with parameters two and five, whose CDF has no simple inverse. Draw a box around its density: as wide as the support, as tall as the highest point, M. Throw darts uniformly into the box: a uniform x, and a uniform height between zero and M. Keep the dart if it lands under the curve; throw it away if it lands above. The x-coordinates of the kept darts are draws from the beta. Of six hundred darts, about forty-one percent were kept, which is the area under the curve, one, divided by the area of the box, M.
Why does it work? A dart at x is kept with chance f of x over M; averaging over the uniform x, the chance of keeping a dart is one over M. The chance that it's kept and lies below t is the same integral, up to t: F of t over M. Divide, and given that a dart was kept, its x has CDF F of t: exactly the target, with no approximation. The number of darts needed for one draw is geometric, with mean M. A loose box wastes darts; the whole art of rejection sampling is a tight envelope.
The box needn't be a box. To sample a normal, which has no bounded support, use a proposal you can already sample: here the Laplace, or double exponential, which inversion handles easily. Scale it up until it covers the normal everywhere; the smallest factor that works is root two e over pi, about one point three two. Draw from the Laplace, and keep each draw with chance equal to the ratio of the normal density to the scaled envelope. The same proof goes through, and about three draws in four are kept.
Building an envelope by hand is an art; for a large family of densities it can be automatic. Call a density log-concave if its logarithm bends downwards everywhere: the normal, the gamma with shape at least one, the logistic, and canonical logistic or Poisson posteriors with log-concave priors in later parts. Then every tangent line to the log density lies above it, so the lowest of a few tangents is an envelope. Exponentiate it, and the envelope is piecewise exponential, easy to sample by inversion. And each time a proposal is rejected, add a tangent at that point: the envelope tightens as the sampler runs. Walter Gilks and Pascal Wild's adaptive rejection sampling, from 1992, was the engine inside the first general-purpose Bayesian software, BUGS.
Rejection has a weakness that grows with dimension. To draw a uniform point in a ball, throw darts into the cube around it and keep those inside. The acceptance rate is the ball's volume over the cube's. In two dimensions it's seventy-nine percent. In ten dimensions, a quarter of a percent. In twenty, two and a half in a hundred million. In high dimensions almost all of a cube's volume lies outside its inscribed ball, and almost every dart misses. One option for high-dimensional Bayesian problems is not to throw darts independently but to walk: a Markov chain that stays where the probability is. That's chapter eleven.
What it does: Darts under Beta(2, 5); the proof; a Laplace envelope for the normal; adaptive rejection for log-concave densities; the curse of dimension.; Numbers (computed): kept 41.3% vs 1/M = 40.7%; normal from Laplace 76%; d-ball from cube: 79% (d = 2), 0.25% (10), 2.5 × 10⁻⁸ (20)
4Special methodsMaster's3 min
The normal quantile is computable, but rotational symmetry gives another efficient sampler. Take two independent uniforms, a point in the unit square. Turn the first into a radius, root minus two log U one, and the second into an angle, two pi U two. The point with that radius and angle has two coordinates that are independent standard normals. George Box and Mervin Muller published it in 1958. Watch the square of uniforms become the round normal cloud.
Why does it work? Part 5 did the hard part. Two independent standard normals have a joint density that depends only on the distance from the centre; in polar coordinates, with the Jacobian r, it separates. So the angle is uniform, independent of the radius, and the radius has the Rayleigh distribution, whose tail is e to the minus r squared over two. And that tail is easy to invert: root minus two log U has exactly that tail. Two inversions and a change of coordinates make two normals. A variant by Marsaglia avoids computing sines and cosines, by rejection from a disc.
For the gamma, there's a rejection sampler so good it almost never rejects. George Marsaglia and Wai Wan Tsang published it in 2000: transform a normal draw by a cubic, then accept or reject with one logarithmic test. Six lines. With shape two and a half, it kept ninety-nine draws in a hundred, and the four thousand draws follow the gamma density. From independent gammas with the same scale come betas, as a ratio, and Dirichlets, exactly as Part 5 showed. Most of the samplers inside NumPy and R are designs like these: one clever transformation per family.
For discrete laws, inversion needs a search; the alias method needs none. Take six outcomes with these probabilities. Multiply each by six, so the average is one. Now rearrange the mass into six columns of equal height, so that each column contains at most two outcomes: its own, and one alias that tops it up. Outcome zero, which needs only a little, is filled up with mass from outcome one. To draw, pick a column uniformly, then a uniform height: below the split, take the column's own outcome; above it, the alias. Two uniforms, no search, for any number of outcomes. Alastair Walker invented it in 1974, and Michael Vose made the table-building fast in 1991. Thirty thousand draws reproduce the probabilities.
And for many variables at once, Part 4 and Part 5 already did the work. Draw a vector of independent normals with Box and Muller, and multiply by the Cholesky factor of the covariance you want, then add the mean. By Part 5's affine rule its covariance is exactly Sigma. Uniforms become normals, normals become correlated normals, and Part 5's copulas turn those into any margins we like. Every random quantity in this series, every World, every simulated study, is a function of a stream of uniforms.
What it does: Box–Muller animated and proved (Rayleigh radius); Marsaglia–Tsang gamma; Walker's alias table; multivariate normals by Cholesky.; Numbers (computed): gamma acceptance 98.7%, mean 2.51; alias frequencies within 0.003 of p
5Monte Carlo integrationBachelor's5 min
Every expectation is an integral, and every integral is an expectation. That's the whole idea of Monte Carlo, the name Stanislaw Ulam, John von Neumann and Nicholas Metropolis used at Los Alamos, after the casino. Pi is four times the chance that a uniform point in the unit square lands inside the quarter circle. So throw darts and count. The running estimate wanders around pi. The two-standard-error funnel is pointwise, not a guarantee for the whole path. After four thousand darts the estimate is shown. Reducing the root mean square error tenfold takes a hundred times as many.
In general: an integral of g against a density f is the expectation of g of X, with X drawn from f. Estimate it by averaging g over n draws; Part 6's weak law makes the average converge. For independent identically distributed draws with finite variance, the standard error is sigma over root n, where sigma, estimated from the same draws, is the spread of g. Look at what's missing from that formula: the dimension. The error falls like one over root n whether x has one coordinate or a thousand, but sigma itself can increase sharply with dimension.
Here's why that matters. Estimate the volume of a ball in d dimensions with a budget near a million points, rounded to a whole number per side. Each random estimate uses exactly the matching grid budget. A grid in d dimensions has only the d-th root of a million points per side: a thousand in two dimensions, but ten in six and four in ten. Its error explodes. The blue curve is the exact standard error of a random estimate, not a realized error. It grows with dimension because the ball becomes a smaller and smaller target inside the cube, but the rate stays one over root N. In one dimension both methods are exact. In ten, the grid error here is much larger than the Monte Carlo standard error. That's why high-dimensional integrals, in Bayesian statistics, physics and finance, are done by simulation.
Random points have a flaw for integration: by chance, they clump and leave gaps. Here are four hundred random points in the square. And four hundred points of the Halton sequence, which writes the index in base two and in base three and reverses the digits: they fill the square deliberately evenly. Integrating with such low-discrepancy points, quasi-Monte Carlo, can make the error fall almost like one over n instead of one over root n, for smooth integrands in moderate dimension. The price is that the error bar must be recovered by randomizing the points, as finance practitioners do every day.
The oldest Monte Carlo experiment is two centuries older than the name. In 1777 Georges-Louis Leclerc, Comte de Buffon, asked: drop a needle on a floor of parallel boards; how often does it cross a line? If the needle is no longer than the spacing, the chance is two times its length over pi times the spacing. Pi appears because the needle's angle is uniform. So counting crossings estimates pi. In the nineteenth century, people actually did it, by hand, thousands of times.
And one of them is a cautionary tale. In 1901 the Italian mathematician Mario Lazzarini reported three thousand four hundred and eight throws of a needle five sixths as long as the spacing, with one thousand eight hundred and eight crossings. That gives three hundred and fifty-five over a hundred and thirteen: pi correct to six decimal places. Too correct. The standard error of an experiment that size is about point oh five: you'd expect the second decimal place to be wrong. Three fifty-five over one thirteen is a famous fraction for pi, and with that needle it can only come out when the number of throws is a multiple of two hundred and thirteen. Three thousand four hundred and eight is sixteen times two hundred and thirteen. Historians suspect he stopped, or chose his count, when the answer looked best. The lesson for every simulation in this course: report the error bar, and decide in advance when to stop.
What it does: π by darts with the √n funnel; σ/√n in any dimension; grid vs MC for the d-ball; Halton points (quasi-MC); Buffon (1777); Lazzarini's suspicious 355/113.; Numbers (computed): 4,000 darts: 3.162; d = 10: grid error 61%, exact MC relative SE about 2.0% at the same rounded grid budget; Buffon SE at 3,408 throws: 0.051
6Simulation studies done rightPractice4 min
A simulation study is an experiment whose subjects are statistical methods, and like any experiment it needs a protocol, written down before you look at results. Tim Morris, Ian White and Michael Crowther summarized one in 2019 with the word ADEMP. Aims: what question, about which methods. Data-generating mechanisms: the worlds you'll simulate, with their sample sizes, effect sizes and tails. Estimands: the true quantity each method is trying to recover. Methods: the procedures, applied to the same simulated data sets. Performance measures: bias, standard error, coverage, power; and every one of them reported with its own Monte Carlo error, because a simulation is itself a random sample.
Here's a small simulation study with a big result. The aim: does the textbook interval for a proportion, the sample share plus or minus one point nine six standard errors, cover the truth ninety-five percent of the time? The data: thirty binomial trials, for forty-nine values of p. For each p, four thousand simulated samples. Red: the coverage, with bars of two Monte Carlo standard errors. It's rarely ninety-five, it's ragged, and near zero and one it collapses below fifty percent. The gold line is the exact coverage, which for this simple problem we can compute by summing the binomial: the simulation is consistent with Monte Carlo noise. These are pointwise bars, not simultaneous guarantees over all forty-nine values. Edwin Wilson's interval from 1927, in green, does far better. Part 11 explains why.
Every number a simulation produces is an estimate, and needs an error bar. A coverage is a proportion of R replicates, so its Monte Carlo standard error is root c times one minus c over R. With four thousand replicates and coverage near ninety-five percent, that's about a third of a percentage point: a reported ninety-four point eight means ninety-four point eight plus or minus point seven, as an approximate ninety-five-percent Monte Carlo interval. Turn it around to plan the study: to resolve a quarter of a point, you need about seventy-six hundred replicates. A bias is an average of R errors, so its standard error is the empirical standard error over root R. Report them; otherwise a difference between methods might be nothing but simulation noise.
Randomness in a study must be controlled. Use one seed, and write it down: anyone can then rerun the study and get the same numbers. Give each scenario its own independent stream, spawned from that seed, keeping assignments stable; appending scenarios preserves existing streams, while reordering can change the others. Apply every method to the same simulated data sets. The comparison is then paired, like a crossover trial, and positive covariance can make the noise in the difference smaller than the noise in each. And never pick the seed that gives the nicest answer: that's Lazzarini's needle again.
All of this is packed into one function in statkit: give it a data-generating mechanism, a method, the true value, the number of replicates and a seed. For the Wald interval at p equal to point one with thirty trials, its coverage is about eighty-one percent, plus or minus about point six. It reports bias and empirical standard error, each with its Monte Carlo error. The Coverage Board that appears throughout this series uses this framework; the empirical-standard-error MCSE uses a normal approximation across replicates.
What it does: ADEMP (Morris, White & Crowther 2019); Wald interval coverage for n = 30 against the exact sum and Wilson; Monte Carlo SEs and planning R; seeds, streams, common random numbers; simulate.; Numbers (computed): Wald coverage 46% at p = 0.02; MCSE 0.0034 at c = 0.95, R = 4,000; p = 0.1: 0.807 ± 0.006
7Variance reductionMaster's4 min
Monte Carlo's error falls like one over root n, so halving it costs four times the computing. Variance reduction makes each draw count for more. Take a test case with a known answer: the integral of e to the u from zero to one, which is e minus one. The antithetic trick: for each uniform U, also use one minus U. Same number of evaluations, but they come in pairs. When U is small, e to the U is low and e to the one minus U is high: the errors in each pair cancel. The variance is multiplied by one plus their correlation, which here is minus point nine seven.
A second trick uses something you already know. The uniforms themselves have a known mean, a half. If the sample of U's happens to be high, e to the U is probably high too, so subtract a multiple of the U's error. The best multiple is the regression slope of e to the U on U, here known analytically as six times three minus e. With an unknown slope, a separate pilot or cross-fitting can preserve unbiasedness; a same-sample fitted slope need not. What remains is the variance that U can't explain, one minus rho squared, and since e to the u is nearly a straight line on the unit interval, rho is point nine nine. Control variates are regression, used to cancel noise.
A third trick comes from survey sampling. Plain uniforms clump by chance, leaving parts of the interval unvisited. Instead, cut the interval into n equal pieces and draw exactly one uniform inside each: stratified sampling. By Part 5's law of total variance, the error now comes only from variation within each piece; the variation between pieces is gone. For our test integral with a thousand draws, the variance falls by a factor of about . Survey statisticians call this stratification, and Part 18 uses it on people instead of numbers.
How much does it help? Four thousand repetitions of each estimator, each using a thousand evaluations. The plain average has a standard deviation of about point oh one six. The antithetic estimator: point oh oh two eight, a variance times smaller. The control variate: point oh oh two, about times smaller. For free, the same accuracy as running the plain simulation thirty or sixty times as long.
The most powerful trick changes where you sample. Suppose we want the chance that a standard normal exceeds four: about three in a hundred thousand. With a hundred thousand plain draws, you'd see about three exceedances, and in about one run in twenty-four, none at all. The estimate is mostly noise. Instead, draw from a normal centred at four, where half the draws exceed four, and reweight each by the ratio of the densities. The expectation is unchanged, by a one-line change of measure. But the variance falls by a factor of several thousand. This is importance sampling, and it's how rare events, from bank failures to particle collisions, are computed.
Importance sampling can also fail, and silently. Its variance involves the target density squared over the proposal. If the proposal has lighter tails than the target, then far out the ratio explodes: a rare draw gets an enormous weight, and the variance can be infinite, Part 6's heavy tails all over again. Worse, the estimate can look perfectly stable for a long time before one draw moves it. The rule: cover the integrand's support, check the second moment of the weights, and inspect them. Heavier tails can help but are not a universal guarantee. Part 27 turns that advice into a diagnostic.
What it does: Antithetic pairs; control variates (regression); stratified sampling; importance sampling for P(Z > 4); when importance sampling fails.; Numbers (computed): variance ÷32 (antithetic), ÷62 (control), ÷8 × 10⁵ (stratified); P(Z > 4): variance ÷6,700
8Markov chainsBachelor's4 min
Many earlier samplers produced independent draws; antithetic pairs deliberately did not. Many of the most useful random processes have memory. In 1913 Andrey Markov took the first twenty thousand letters of Pushkin's novel in verse, Eugene Onegin, and classified each as a vowel or a consonant. The chance of a vowel was not the same after a vowel as after a consonant: the letters were dependent, but in a simple way. A time-homogeneous Markov chain is a sequence in which the next state depends on the past only through the present state: given where you are now, where you've been doesn't matter. All of its behaviour is in one table of transition probabilities.
Markov's own numbers make a perfect first example. After a vowel, the next letter of Onegin was a vowel only about thirteen percent of the time; after a consonant, sixty-six percent. A two-state chain spends a long-run share of its time in each state that's easy to compute: the chance of entering a state, over the total chance of switching. For vowels: about forty-three percent. Markov's direct count of vowels in the text: forty-three point two percent. His real point was philosophical: the law of large numbers, which Nekrasov had claimed required independence, holds for dependent sequences too.
Here's a toy chain: tomorrow's weather, given today's. Three states: sunny, cloudy, rainy. From sunny, it stays sunny with chance point seven, turns cloudy with point two, rainy with point one. Each state has its own row of probabilities. Collect them into a matrix. Row i says where tomorrow goes from state i, so each row adds up to one.
Now think of probability as a fluid flowing between the states. Start certain that today is sunny: all the mass on one bar. Tomorrow's distribution is today's row vector times P: Part 2's law of total probability, as matrix multiplication. Step after step, the mass redistributes, and settles: after about ten days it barely changes. Forty-six percent sunny, thirty-two cloudy, twenty-two rainy. Start from rain instead and you end up in the same place: the chain forgets where it began.
How fast does it forget? Plot the distance to the settled distribution, on a log scale: a straight line, so the distance shrinks by the same factor every day. That factor is the transition matrix's second-largest eigenvalue magnitude, here point four six, governing the asymptotic rate for this diagonalizable chain. The largest is always exactly one, and its left eigenvector is the settled distribution itself, which is the subject of the next chapter. The closer the second eigenvalue is to one, the slower the chain forgets.
There's a second way to see the stationary law. Instead of evolving the whole distribution, simulate one long run of the chain: here are its first sixty-four days. Track the share of sunny, cloudy and rainy days so far. After a few thousand days they settle onto the stationary probabilities. That's the ergodic theorem for Markov chains: for a finite irreducible chain the time average converges almost surely to the stationary expectation as the run grows. It's why one long run of a Markov chain, in chapter eleven, can estimate stationary expectations, with Monte Carlo uncertainty that accounts for autocorrelation.
What it does: Markov's Onegin (1913) and its two-state chain; the weather chain; probability as a flowing fluid; the ergodic theorem along one path; geometric convergence by the second eigenvalue.; Numbers (computed): vowels: chain 0.432 vs count 43.2%; π = (19, 13, 9)/41; λ₂ = 0.462
9Stationary distributionsMaster's4 min
The settled distribution is the one that doesn't change in a step. A row vector pi with pi times P equal to pi: a left eigenvector of the transition matrix, with eigenvalue one, scaled to add up to one, with nonnegative entries. Each equation says that the mass flowing into a state equals the mass already there. For the weather chain, solving them gives nineteen forty-firsts sunny, thirteen forty-firsts cloudy, nine forty-firsts rainy. And a theorem of Oskar Perron and Georg Frobenius guarantees, for a finite chain that can get from anywhere to anywhere and doesn't cycle, that this distribution exists, is unique, and is reached from every start.
There's an easier condition to check. Detailed balance: for every pair of states, the flow of probability from i to j equals the flow back from j to i. Sum it over i, and the right side becomes pi j, since each row of P sums to one. So detailed balance implies stationarity. Stationarity balances the total flow into each state; detailed balance balances every pair. A chain that satisfies it is reversible: filmed and played backwards, it looks statistically the same when started at stationarity. And it's the easy way to design a chain with any stationary distribution we want, which is exactly what chapter eleven will do.
Detailed balance makes some stationary distributions obvious. A random walk on a graph steps to a neighbour chosen at random; the number on each node is its degree, how many neighbours it has. Guess that the stationary chance of a node is its degree, over twice the number of edges. Check detailed balance: pi i times one over degree i is one over twice the edges, the same in both directions. So the guess is right: a random walker spends time in proportion to how connected a node is. Circle areas are proportional to stationary probability.
The most valuable stationary distribution ever computed belonged to a chain on the web. Pages link to pages. Imagine a surfer who, at each step, follows a random link from the current page with chance point eight five, and otherwise jumps to a page chosen at random. That's a Markov chain on the pages, and its stationary distribution is PageRank: the long-run share of time the surfer spends on each page. Sergey Brin and Larry Page built a search engine on it in 1998. The random jump guarantees the conditions of the convergence theorem. On this little web of seven pages, power iteration converges in a few dozen steps, and the page that many others link to, with a third of the surfer's time, comes out on top.
One condition in that theorem is easy to overlook. A chain on two states that always switches. Half and half is stationary. But start on the left, and the chance of being on the left goes one, zero, one, zero, for ever. It never converges, because the chain is periodic: it can only return at even times. The cure is a little laziness: stay put with chance a half. Aperiodicity ensures convergence in distribution here; even this periodic chain has convergent time averages.
What it does: Left eigenvectors and Perron–Frobenius; detailed balance and reversibility; random walk on a graph (π ∝ degree); PageRank; periodicity.; Numbers (computed): PageRank (0.30, 0.15, 0.33, 0.02, 0.09, 0.05, 0.07)
10Mixing: seven shufflesPhD4 min
How many times must you shuffle a deck of cards before it's truly mixed? This is a question about a Markov chain whose states are the orderings of the deck. Here's a ten-card deck and the standard model of a riffle shuffle. First, cut the deck: the size of the top packet is binomial, so usually near the middle. Then riffle: let cards fall one at a time from the two packets, each time choosing a packet with probability proportional to how many cards it still holds. This model, due to Edgar Gilbert and Claude Shannon and independently Jim Reeds, matches how real people shuffle surprisingly well. Watch three shuffles.
How close is the deck to uniform after k shuffles? There are fifty-two factorial orderings, about eight times ten to the sixty-seven, so we can't list them. Dave Bayer and Persi Diaconis found a way around it in 1992. After k riffle shuffles, the chance of any particular ordering depends only on its number of rising sequences, one plus the descents of the inverse deck permutation: consecutive labels appearing in their original order. A single shuffle creates at most two; k shuffles at most two to the k. So the total variation distance to the uniform, the largest error in the probability of any event, is a sum of only fifty-two terms, weighted by the Eulerian numbers that count orderings with each number of rising sequences. We can compute it exactly.
Here's the answer for fifty-two cards. After one, two, three, even four shuffles the distance is essentially one: the deck is as far from random as it can be, and a clever gambler could exploit it. At five it starts to drop, point nine two; at six, point six one. At seven, a third, and from there it halves with every shuffle. Bayer and Diaconis's verdict, which made the newspapers: seven is a useful rule of thumb, but total variation is still a third; the required number depends on your tolerance, and further shuffles keep reducing the discrepancy.
Can we trust the formula? Check it by simulation. With five cards there are only a hundred and twenty orderings, so we can shuffle sixty thousand decks with our generator and count. The simulated distances track the exact ones, until they reach the simulation's own noise floor, about two percent: this positive bias comes from adding absolute count errors, not a floor in the true distance. The aggregate discrepancy is about that much. An exact answer and a simulation, each checking the other: that's the habit this part is trying to build.
The shape of that curve has a name: the cutoff phenomenon. The distance stays near one, then falls off a cliff, around one and a half times the base-two log of the number of cards. For fifty-two cards the drop begins at five and is a third by seven. Other ways of shuffling are much slower: the overhand shuffle, sliding small packets from hand to hand, needs thousands. The same question, how long until a chain has forgotten where it started, is the central practical question of Markov chain Monte Carlo, coming next and in Part 27. And the answer, like the deck's, depends on the chain.
What it does: The GSR riffle animated; rising sequences and the Bayer–Diaconis formula; total variation for 52 cards; a 5-card simulation check; the cutoff phenomenon.; Numbers (computed): TV: 1.000 (k ≤ 4), 0.924, 0.614, 0.334, 0.167, 0.085
11The Metropolis algorithmMaster's5 min
Chapter three ended with a problem: in high dimensions, independent darts almost all miss. The fix was found at Los Alamos. In 1953 Nicholas Metropolis, Arianna and Marshall Rosenbluth, and Augusta and Edward Teller published a method for sampling arrangements of molecules on the MANIAC computer. Arianna Rosenbluth wrote the program. Seventeen years later Keith Hastings generalized it. It samples from a density known only up to a constant, which is exactly the situation of Bayesian statistics, where the posterior's normalizing constant is an integral that may be difficult to compute.
The algorithm fits in six lines. From the current point x, propose a random step to y. If y has higher density, move there. If lower, move there anyway with chance equal to the ratio of the densities; otherwise stay put, and record x again. Only the ratio f of y over f of x is used, so any constant multiplying f cancels. Uphill moves are always taken; downhill moves sometimes; and the result is a walk that spends time in each region in proportion to its probability.
Why does it work? Chapter nine's detailed balance. The off-diagonal transition density from x to y is the proposal density at y, times the acceptance probability. Multiply by f of x: you get the proposal density times the smaller of f of x and f of y, which is symmetric in x and y, because the proposal is. So the flow from x to y equals the flow from y to x: detailed balance, and f is the chain's stationary distribution. Run it long enough and its states are dependent draws with a distribution approaching normalized f, under irreducibility and appropriate recurrence and aperiodicity conditions. Detailed balance alone establishes stationarity.
The one thing you must choose is the step size. Here's a target with two humps, at minus two and plus two, and the first six hundred steps of three longer chains; acceptance rates use all six thousand steps. With tiny steps, nearly every proposal is accepted, but the chain crawls, and it never leaves the hump where it started. With steps of one and a half, about half the proposals are accepted and the chain moves freely between the humps. With huge steps, most proposals land in empty regions and are rejected: the chain sits still for long stretches, then jumps. A high acceptance rate is not a good sign by itself; neither is a low one.
Six thousand steps of the well-tuned chain: the histogram of its states matches the target, both humps in the right proportions. Compare the three chains' estimates of the mean. The truth is point eight. The well-tuned chain and the big-step chain get close. The tiny-step chain reports two point oh five, and its histogram and acceptance rate alone can mislead: it simply never found the other hump. That's the danger of Markov chain Monte Carlo, and Part 27 builds the diagnostics against it.
One special case deserves a first look. When the conditional distribution of each coordinate, given all the others, is easy to sample, update one coordinate at a time from its conditional. For a correlated normal pair, those conditionals are Part 5's: normal, centred at rho times the other coordinate. The chain moves in horizontal and vertical steps, and every step is accepted. It's called Gibbs sampling, after the physicist, and Alan Gelfand and Adrian Smith's 1990 paper put it at the centre of Bayesian statistics. Notice the staircase: when the coordinates are strongly correlated, the steps are short and the chain mixes slowly, a problem Part 27 takes on.
This was a first look; Part 27 does it in full. The draws are dependent, so a chain of six thousand steps usually carries less information for a given estimand than six thousand independent draws; negative autocorrelation can improve efficiency. The start matters until the chain has mixed, so early steps are often discarded, but burn-in cannot fix a chain that never explores missing modes. Running several chains from scattered starts, and checking that they agree, can reveal the tiny-step failure we just saw. In high dimensions, random-walk proposals often need to shrink in common models, and better proposals use the gradient of the density: Hamiltonian Monte Carlo. And this is the machine that samples posterior distributions in Bayesian statistics, once the conjugate formulas of Part 15 run out.
What it does: Los Alamos (1953); the six-line algorithm; detailed balance; three step sizes on a two-humped target; Gibbs sampling, first look; lessons for Part 27.; Numbers (computed): acceptance 97% / 57% / 9%; means 2.05 / 0.89 / 0.89 vs truth 0.80
Recap, problems, and the road aheadAll tracks3 min
Part seven in thirteen lines. Arithmetic randomness is a state of sin, and RANDU's triples fell on fifteen planes. Linear congruential generators have periods and lattices; PCG hides them, and statistical tests can catch what remains. The inverse CDF turns one uniform into any distribution with a usable inverse. Rejection keeps the darts under a curve, at a rate of one over M. Box and Muller make normals from polar coordinates, Marsaglia and Tsang make gammas, and Walker's alias table makes discrete draws in constant time. Monte Carlo integration has error sigma over root n in any dimension; Buffon's needle estimates pi, and Lazzarini's needle teaches honesty. Simulation studies need a protocol, Monte Carlo standard errors and controlled seeds. Antithetic pairs, control variates and importance sampling make each draw count for more. A Markov chain moves probability like a fluid toward its stationary law; detailed balance builds chains, random walks favour hubs, and PageRank ranks the web. Seven riffle shuffles leave about a third in total variation; the mixing threshold depends on tolerance, with an asymptotic cutoff. And Metropolis builds a chain with any stationary law we like.
Where it comes back. statkit's generator and harness support simulation work from here on: sampling distributions in Part 8, coverage in Part 11, the bootstrap in Part 16, thousands of tests in Part 33. Importance sampling returns in Bayesian computation and model comparison. Markov chains return in time series and, with full rigour, in Part 44. And Metropolis grows into the whole of Bayesian computation in Part 27.
Six problems, with full solutions in the README. Periods of two small generators; inverse-CDF samplers for the Pareto and the logistic; a rejection sampler's efficiency; the cost of a Monte Carlo integral; a two-state chain; and the proof that Metropolis works. Pause here if you want to try them.
The books and papers this part follows: Knuth's second volume, Devroye's encyclopedia of samplers, Robert and Casella, Owen on Monte Carlo, and Levin and Peres on mixing, with the original papers from von Neumann to Bayer and Diaconis.
Seven parts of sixty-five. We can now make randomness, shape it into any distribution, and use it to test methods honestly. Next, we turn the machine on statistics themselves: draw sample after sample from the World, compute a mean, a variance, a t statistic each time, and watch how they vary. That variation has exact laws, discovered by a brewer at Guinness in 1908. Part 8: from sample to population.
Where it goes next. statkit.random and the simulation harness run the sampling distributions of Part 8, the coverage of Part 11, the bootstrap of Part 16 and the thousands of tests of Part 33; importance sampling and Metropolis grow into Bayesian computation in Parts 15, 26 and 27; Markov chains return in time series (Part 17) and with full rigour in Part 44.
Key results
The part's results in one place, for revision.
Try it
Lab 7 · A bad generator and an honest simulation study
Show that RANDU passes a one-dimensional test while 9x - 6y + z takes only fifteen values on its triples, then use statkit's simulate to estimate the coverage of the textbook interval for a proportion (n = 30) and compare it, within Monte Carlo error, with the exact binomial sum.
python -m videos.stats.labs 7
needs numpy, scipy, matplotlib · download lab07.py ·
source on GitHubRANDU, 300,000 numbers in 10 bins chi-squared 4.3 on 9 df, p = 0.89
RANDU, 100,000 triples in 1,000 cells chi-squared 1593 on 999 df, p = 5e-30
values of 9x - 6y + z on RANDU's triples 15 (from -5 to 9)
values of 9x - 6y + z on PCG32's triples 8998 of 8998
Wald coverage at p = 0.02 0.451 +/- 0.008 (exact 0.454)
Wald coverage at p = 0.1 0.805 +/- 0.006 (exact 0.809)
Wald coverage at p = 0.5 0.953 +/- 0.003 (exact 0.957)
A generator can pass one test and fail another, so it is tested many ways; and a simulated coverage is an estimate, here within two or three Monte Carlo standard errors of the exact answer, which is far below 95% for small p.
The code (97 lines; it asserts its own result)
"""Lab 7: catch RANDU on its fifteen planes, then run a simulation study with its Monte Carlo errors."""
import numpy as np
from scipy import stats
from videos.coursekit import labs
from explainer.stats.kit import random as skr
from explainer.stats.kit import tests as skt
TITLE = "A bad generator and an honest simulation study"
GOAL = ("Show that RANDU passes a one-dimensional test while 9x - 6y + z takes only fifteen values on its triples, "
"then use statkit's simulate to estimate the coverage of the textbook interval for a proportion (n = 30) "
"and compare it, within Monte Carlo error, with the exact binomial sum.")
TASKS = [
"Swap the method for Wilson's interval, (p + z^2/2n +/- z sqrt(p(1 - p)/n + z^2/4n^2)) / (1 + z^2/n) with "
"z = 1.96. How near 95% does its coverage stay across p?",
"Cut reps to 400. How wide do the bars of two Monte Carlo standard errors become, and can you still tell "
"p = 0.3 from 95%?",
"Replace randu by lcg(5, 3, 16, seed, n) and plot consecutive pairs. How many lines do they fall on?",
]
N_TRIALS = 30
def wald(x):
"""The textbook 95% interval for a proportion from x successes in N_TRIALS trials."""
p = x / N_TRIALS
half = 1.96 * np.sqrt(p * (1 - p) / N_TRIALS)
return p, p - half, p + half
def exact_coverage(p):
x = np.arange(N_TRIALS + 1)
_, lo, hi = wald(x)
return float(np.sum(stats.binom.pmf(x, N_TRIALS, p) * ((lo <= p) & (p <= hi))))
def run(seed=0):
lab = labs.Lab()
# 1. RANDU: uniform in one dimension, fifteen planes in three.
ints = skr.randu(2 * seed + 1, 300_000) # an odd seed; seed 0 is the film's
cells = np.minimum(ints * 10 // skr.M31, 9).astype(int)
one_d = skt.chisq_test(np.bincount(cells, minlength=10), np.full(10, 0.1))
c3 = cells.reshape(-1, 3) @ np.array([100, 10, 1]) # each non-overlapping triple's cell in a 10 x 10 x 10 grid
three_d = skt.chisq_test(np.bincount(c3, minlength=1000), np.full(1000, 0.001))
k = (9 * ints[:-2] - 6 * ints[1:-1] + ints[2:]) / skr.M31
planes = np.unique(k)
pcg = skr.PCG32(seed + 42).random(9000)
k_pcg = 9 * pcg[:-2] - 6 * pcg[1:-1] + pcg[2:]
lab.row("RANDU, 300,000 numbers in 10 bins", f"chi-squared {one_d['chi2']:.1f} on 9 df, p = {one_d['p']:.2f}")
lab.row("RANDU, 100,000 triples in 1,000 cells", f"chi-squared {three_d['chi2']:.0f} on 999 df, p = {three_d['p']:.0e}")
lab.row("values of 9x - 6y + z on RANDU's triples", f"{len(planes)} (from {planes.min():.0f} to {planes.max():.0f})")
lab.row("values of 9x - 6y + z on PCG32's triples", f"{len(np.unique(k_pcg))} of {len(k_pcg)}")
assert one_d["p"] > 0.001, "one coordinate at a time, RANDU looks uniform"
assert three_d["p"] < 1e-6, "three at a time, it does not"
assert len(planes) == 15 and np.all(planes == np.round(planes)), "every RANDU triple lies on one of 15 planes"
assert len(np.unique(k_pcg)) > 0.99 * len(k_pcg), "PCG32's triples do not"
# 2. A simulation study (ADEMP): the coverage of the Wald interval, each estimate with its Monte Carlo SE.
reps, ps = 4000, [0.02, 0.05, 0.1, 0.2, 0.3, 0.5, 0.7, 0.9]
sims = []
for i, p in enumerate(ps):
out = skr.simulate(lambda rng, p=p: rng.binomial(N_TRIALS, p), wald, p, reps, seed=1000 * seed + i)
truth = exact_coverage(p)
sims.append(out)
if p in (0.02, 0.1, 0.5):
lab.row(f"Wald coverage at p = {p}", f"{out['coverage']:.3f} +/- {out['coverage_mcse']:.3f} (exact {truth:.3f})")
assert abs(out["coverage"] - truth) < 4 * np.sqrt(truth * (1 - truth) / reps), "simulation within Monte Carlo error"
assert abs(out["bias"]) < 4 * out["bias_mcse"], "the sample share is unbiased"
assert exact_coverage(0.02) < 0.5 and exact_coverage(0.1) < 0.85, "the textbook interval breaks its 95% promise"
assert abs(skr.mc_se(np.r_[np.ones(3800), np.zeros(200)]) - np.sqrt(0.95 * 0.05 / 4000)) < 1e-5, "MCSE of a proportion"
lab.note = ("A generator can pass one test and fail another, so it is tested many ways; and a simulated coverage "
"is an estimate, here within two or three Monte Carlo standard errors of the exact answer, which "
"is far below 95% for small p.")
fig, ax = labs.figure(2, size=(11, 4.2))
trip = np.column_stack([ints[:-2], ints[1:-1], ints[2:]])[:3000] / skr.M31
along = trip @ np.array([2, 3, 0]) / np.sqrt(13) # a direction inside the planes
across = trip @ np.array([9, -6, 1]) / np.sqrt(118) # the planes' normal
ax[0].scatter(along, across, s=3, color=labs.RED, label="RANDU")
ptrip = np.column_stack([pcg[:-2], pcg[1:-1], pcg[2:]])[:3000]
ax[0].scatter(ptrip @ np.array([2, 3, 0]) / np.sqrt(13) + 1.6, ptrip @ np.array([9, -6, 1]) / np.sqrt(118), s=3,
color=labs.GREEN, label="PCG32 (shifted right)")
ax[0].set(title="3,000 triples seen edge-on to RANDU's planes", xlabel="(2x + 3y)/sqrt(13)",
ylabel="(9x - 6y + z)/sqrt(118)")
ax[0].legend(loc="upper center", ncol=2, markerscale=3)
ax[0].set_ylim(-0.6, 1.15)
grid = np.linspace(0.01, 0.99, 197)
ax[1].plot(grid, [exact_coverage(p) for p in grid], color=labs.GOLD, lw=1.2, label="exact (binomial sum)")
ax[1].errorbar(ps, [o["coverage"] for o in sims], yerr=[2 * o["coverage_mcse"] for o in sims], fmt="o",
color=labs.RED, capsize=3, label="simulate: 4,000 replicates, +/- 2 MCSE")
ax[1].axhline(0.95, color=labs.MUTED, ls="--", lw=1)
ax[1].set(title="Coverage of p-hat +/- 1.96 SE, n = 30", xlabel="true p", ylabel="coverage", ylim=(0.4, 1.0))
ax[1].legend(loc="lower center")
lab.fig = fig
return lab
Now change it
- Swap the method for Wilson's interval, (p + z^2/2n +/- z sqrt(p(1 - p)/n + z^2/4n^2)) / (1 + z^2/n) with z = 1.96. How near 95% does its coverage stay across p?
- Cut reps to 400. How wide do the bars of two Monte Carlo standard errors become, and can you still tell p = 0.3 from 95%?
- Replace randu by lcg(5, 3, 16, seed, n) and plot consecutive pairs. How many lines do they fall on?
Problems, with solutions
Try each problem before opening its solution.
1. Two periods. Show that \(x \mapsto (5x + 3) \bmod 16\) has full period, and find the period of \(x \mapsto 5x \bmod 16\) started at 1.
Solution
For x ↦ (5x + 3) mod 16, the Hull–Dobell conditions hold, so the period is the full 16:
- c = 3 is coprime to 16;
- a − 1 = 4 is divisible by 2, the only prime factor of 16;
- a − 1 is also divisible by 4, as it must be since 4 divides 16.
For x ↦ 5x mod 16 from 1, the sequence is 1, 5, 9, 13, 1, …, so the period is 4.
2. Inversion. Derive inverse-CDF samplers for the Pareto (\(P(X > x) = (x_m/x)^\alpha\)) and the logistic (\(F(x) = 1/(1 + e^{-x})\)).
Solution
- Pareto: F(x) = 1 − (x_m/x)^α for x ≥ x_m. Solving u = F(x) gives x = x_m (1 − u)^{−1/α}. Since 1 − U is also uniform, x_m U^{−1/α} works too.
- Logistic: u = 1/(1 + e^{−x}) gives x = log(u/(1 − u)).
3. Rejection for 6x(1 − x). Rejection from a uniform box for \(f(x) = 6x(1 - x)\) on \([0, 1]\): find \(M\), the acceptance rate, and the mean number of darts per draw.
Solution
The density peaks at x = 1/2 with value 3/2, so M = 3/2. The acceptance rate is 1/M = 2/3, and the number of darts per draw is geometric with mean M = 1.5.
4. A Monte Carlo integral. g(U) = √(1 − U²).
Solution
I = π/4. Then E g² = ∫₀¹ (1 − x²) dx = 2/3, so
Var g(U) = 2/3 − π²/16 = 0.0498,
and σ = 0.223. The standard error is σ/√n, so SE = 0.001 needs n = (0.223/0.001)², at least 49,817 using the unrounded variance. (Antithetic or stratified sampling would cut this by a large factor.)
5. A two-state chain. For \(P = \begin{pmatrix} 1 - a & a \ b & 1 - b \end{pmatrix}\), find the stationary law and the second eigenvalue.
Solution
Assume 0 ≤ a,b ≤ 1. If a=b=0, P=I and every distribution is stationary. Otherwise solving πP = π gives π = (b/(a + b), a/(a + b)); detailed balance π₁a = π₂b gives the same answer at once. The trace is 2 − a − b = 1 + λ₂, so λ₂ = 1 − a − b. When 0 < a+b < 2, the chain forgets its start geometrically at rate |1 − a − b|.
- When a + b = 1, it forgets in one step.
- When a = b = 1, it alternates for ever: periodic, with λ₂ = −1.
6. Metropolis with an unnormalized f. Show that Metropolis with a symmetric proposal satisfies detailed balance for an unnormalized \(f\).
Solution
For y ≠ x, the off-diagonal transition density is T(x → y) = q(y | x) min(1, f(y)/f(x)). Then
f(x) T(x → y) = q(y | x) min(f(x), f(y)).
This is symmetric in x and y because q is, so detailed balance holds and f/∫f is stationary, assuming 0 < ∫f < ∞. Ergodic convergence requires additional chain conditions. If f = c f̃ with c unknown, then f(y)/f(x) = f̃(y)/f̃(x): the constant cancels, and the chain run with f̃ is the same chain.
Notes and sources
Where it comes back
| Idea | Returns in |
|---|---|
| statkit.random, the simulation harness, the Coverage Board | 8, 11, 16, 33 |
| Monte Carlo error, simulation-study design | 11, 16, 28, 59 |
| inversion of the ECDF: the bootstrap | 16 |
| importance sampling | 27, 28 |
| stratification | 18 |
| Markov chains, stationary laws, ergodicity | 17, 27, 44 |
| mixing and convergence diagnostics | 27, 53 |
| Metropolis, Gibbs, MCMC | 15, 26, 27 |
Sources
- Generators.
- J. von Neumann, "Various techniques used in connection with random digits", NBS Applied Math. Series 12 (1951).
- D. H. Lehmer (1949, publ. 1951); T. Hull & A. Dobell, SIAM Review 4 (1962); R. Coveyou & R. MacPherson, JACM 14 (1967).
- G. Marsaglia, "Random numbers fall mainly in the planes", PNAS 61 (1968).
- M. Matsumoto & T. Nishimura, ACM TOMACS 8 (1998); M. E. O'Neill, "PCG…" (2014).
- P. L'Ecuyer & R. Simard, "TestU01", ACM TOMS 33 (2007).
- Samplers.
- G. Box & M. Muller, Ann. Math. Statist. 29 (1958); G. Marsaglia & T. Bray (1964).
- G. Marsaglia & W. W. Tsang, ACM TOMS 26 (2000).
- A. Walker, Electronics Letters 10 (1974); M. Vose, IEEE TSE 17 (1991).
- W. Gilks & P. Wild, Applied Statistics 41 (1992); M. Wichura, AS 241 (1988).
- Monte Carlo.
- G. Buffon, Essai d'arithmétique morale (1777); M. Lazzarini (1901), and N. T. Gridgeman, "Geometric probability and the number π", Scripta Math. 25 (1960).
- J. Halton (1960); I. Sobol' (1967).
- T. Morris, I. White & M. Crowther, Statistics in Medicine 38 (2019).
- Markov chains.
- A. Markov (1906; 1913, on Eugene Onegin); B. Hayes, "First links in the Markov chain", American Scientist 101 (2013).
- S. Brin & L. Page (1998).
- E. Gilbert (1955); J. Reeds (1981); D. Bayer & P. Diaconis, "Trailing the dovetail shuffle to its lair", Ann. Appl. Probab. 2 (1992).
- MCMC.
- N. Metropolis, A. Rosenbluth, M. Rosenbluth, A. Teller & E. Teller, J. Chem. Phys. 21 (1953).
- W. K. Hastings, Biometrika 57 (1970).
- S. Geman & D. Geman (1984); A. Gelfand & A. Smith, JASA 85 (1990).
- Textbooks.
- D. Knuth, TAOCP vol. 2 (3rd ed., 1997).
- L. Devroye, Non-Uniform Random Variate Generation (1986).
- C. Robert & G. Casella, Monte Carlo Statistical Methods (2nd ed., 2004).
- A. Owen, Monte Carlo Theory, Methods and Examples.
- D. Levin & Y. Peres, Markov Chains and Mixing Times (2nd ed., 2017).
About this partfrom its README
Part 7 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), in Stage I, Bachelor's: Foundations. Every simulation in Parts 1–6 ran on a machine that can only follow instructions. This part builds the randomness, shapes it into any distribution, and learns to use it honestly. PCG stream parameters are distinct, rather than a proof of independent or nonoverlapping outputs. It ends with Markov chains, the engine of modern Bayesian computation.
It opens with John von Neumann's warning (1951) that arithmetic randomness is "a state of sin". It then turns 3,000 consecutive triples from IBM's RANDU in 3D until all of them fall on 15 planes (Marsaglia 1968). From there:
- linear congruential generators, their periods and lattices;
- PCG, and how generators are tested;
- the inverse CDF;
- rejection sampling;
- Box–Muller, Marsaglia–Tsang and Walker's alias table;
- Monte Carlo integration, from Buffon's needle to Lazzarini's;
- simulation studies with Monte Carlo standard errors;
- variance reduction;
- Markov chains, their stationary laws, PageRank, the seven-shuffle theorem and the Metropolis algorithm.
Numerical examples are cached in compute.py; small seeded harness, stratification, and chain demonstrations are evaluated in their scenes. The generators and samplers there are statkit's
own; the riffle-shuffle distances are exact. For a forward riffle with the deck listed in final order, rising sequences are one plus descents of the inverse permutation; inversion preserves the Eulerian counts used in TV. The d-ball comparison uses the same actual budget m^d for the grid error and exact Monte Carlo standard error. Displayed histograms retain omitted tail mass in their denominators. The control-variate comparison uses the known population coefficient 6(3−e), rather than fitting it to the same draws.
Built in this part: statkit.random (explainer/stats/kit/random.py),
tested against SciPy in tests/test_stats_kit_random.py. It contains:
- generators:
randu,lcg,PCG32; - samplers:
inverse_cdf,discrete_inverse,rejection,box_muller,marsaglia_tsang,AliasTable; - the simulation-study harness:
streams(independent, reproducible generators),mc_se, andsimulate, which reports bias, empirical SE and coverage, each with its Monte Carlo SE.
The harness provides the Coverage Board framework; empirical-SE MCSE uses a normal approximation across replicates. NSpace.cloud (in explainer/stats/viz.py) draws thousands of
points in a turnable ℝ³ with one updater.
Chapter notes
| # | Chapter | What it does | Numbers (computed) |
|---|---|---|---|
| 0 | A state of sin | Von Neumann (1951); his middle-square method and its cycles; RANDU's triples turned edge-on in 3D; PCG32's cube; the objectives. | 2100 → 4100 → 8100 → 6100 → 2100; 9x − 6y + z takes 15 integer values |
| 1 | Pseudo-random generators | Lehmer's LCG (1949); periods on a 64-hour clock and Hull–Dobell; the lattice of pairs and the spectral test; PCG32 in four lines; the Mersenne Twister; χ², runs and 3-D tests. | period 16 vs 64; RANDU 1-D χ² p = 0.89 but 3-D p = 5 × 10⁻³⁰; PCG32 p = 0.87, 0.16 |
| 2 | The inverse CDF | Proof; the exponential by −log(1 − U); 4,000 draws; discrete inversion; inverting the ECDF is resampling (the bootstrap); the normal's numerical quantile. | frequencies 0.10, 0.23, 0.30, 0.21, 0.15 vs 0.10, 0.25, 0.30, 0.20, 0.15 |
| 3 | Rejection sampling | Darts under Beta(2, 5); the proof; a Laplace envelope for the normal; adaptive rejection for log-concave densities; the curse of dimension. | kept 41.3% vs 1/M = 40.7%; normal from Laplace 76%; d-ball from cube: 79% (d = 2), 0.25% (10), 2.5 × 10⁻⁸ (20) |
| 4 | Special methods | Box–Muller animated and proved (Rayleigh radius); Marsaglia–Tsang gamma; Walker's alias table; multivariate normals by Cholesky. | gamma acceptance 98.7%, mean 2.51; alias frequencies within 0.003 of p |
| 5 | Monte Carlo integration | π by darts with the √n funnel; σ/√n in any dimension; grid vs MC for the d-ball; Halton points (quasi-MC); Buffon (1777); Lazzarini's suspicious 355/113. | 4,000 darts: 3.162; d = 10: grid error 61%, exact MC relative SE about 2.0% at the same rounded grid budget; Buffon SE at 3,408 throws: 0.051 |
| 6 | Simulation studies done right | ADEMP (Morris, White & Crowther 2019); Wald interval coverage for n = 30 against the exact sum and Wilson; Monte Carlo SEs and planning R; seeds, streams, common random numbers; simulate. |
Wald coverage 46% at p = 0.02; MCSE 0.0034 at c = 0.95, R = 4,000; p = 0.1: 0.807 ± 0.006 |
| 7 | Variance reduction | Antithetic pairs; control variates (regression); stratified sampling; importance sampling for P(Z > 4); when importance sampling fails. | variance ÷32 (antithetic), ÷62 (control), ÷8 × 10⁵ (stratified); P(Z > 4): variance ÷6,700 |
| 8 | Markov chains | Markov's Onegin (1913) and its two-state chain; the weather chain; probability as a flowing fluid; the ergodic theorem along one path; geometric convergence by the second eigenvalue. | vowels: chain 0.432 vs count 43.2%; π = (19, 13, 9)/41; λ₂ = 0.462 |
| 9 | Stationary distributions | Left eigenvectors and Perron–Frobenius; detailed balance and reversibility; random walk on a graph (π ∝ degree); PageRank; periodicity. | PageRank (0.30, 0.15, 0.33, 0.02, 0.09, 0.05, 0.07) |
| 10 | Mixing: seven shuffles | The GSR riffle animated; rising sequences and the Bayer–Diaconis formula; total variation for 52 cards; a 5-card simulation check; the cutoff phenomenon. | TV: 1.000 (k ≤ 4), 0.924, 0.614, 0.334, 0.167, 0.085 |
| 11 | The Metropolis algorithm | Los Alamos (1953); the six-line algorithm; detailed balance; three step sizes on a two-humped target; Gibbs sampling, first look; lessons for Part 27. | acceptance 97% / 57% / 9%; means 2.05 / 0.89 / 0.89 vs truth 0.80 |
| 12 | Outro | Recap, payoffs, problems, references, the Transcript, Part 8's question. | — |
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Hook: von Neumann (1951) and RANDU. Points of RANDU falling on 15 planes in 3D (Marsaglia 1968).
- Pseudo-random generators. LCGs (Lehmer 1949); periods; a PCG-style generator built; testing randomness (χ², runs, spectral tests).
- Inverse CDF. The probability integral transform, proved; discrete inversion.
- Rejection sampling (von Neumann 1951). Correctness and efficiency 1/M.
- Special methods. Box–Muller; Marsaglia–Tsang gamma; Walker's alias method; the multivariate normal by Cholesky.
- Monte Carlo integration. Error σ/√n in any dimension; Buffon's needle (1777).
- Simulation studies done right (Morris, White & Crowther 2019).
- Aims, data-generating mechanisms, estimands, methods, performance measures.
- Seeds and independent streams; Monte Carlo standard errors; the Coverage Board protocol (§3) explained.
- Variance reduction. Antithetic and control variates; importance sampling, first look.
- Markov chains. Transition matrices; the chain as a flow of probability mass.
- Stationary distributions. Left eigenvectors; detailed balance; random walks on graphs; PageRank.
- Mixing. Shuffling a deck: the riffle-shuffle curve and its cutoff near seven shuffles (Bayer & Diaconis 1992), computed.
- The Metropolis algorithm, first look. Sampling a known shape by a walk that accepts or rejects (Part 27 does it in full).
- Outro.
Built: statkit.random and the simulation-study harness used by every later part.
Build the film
python -m videos.stats.stats7.compute # the part's numbers, into .cache/stats7
python tools/build.py stats7 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats7 Hook # one chapter, silent, with a contact sheet
Scenes: videos/stats/stats7. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.stats.stats7.compute # once: every computed item (about a minute; cached in .cache/stats7)
python tools/build.py stats7 -q l # fast 480p preview
python tools/build.py stats7 # 1080p30 -> renders/stats7.mp4
python tools/qa_scene.py stats7 Hook # one chapter, silent, with a contact sheet
python tools/lecture_length.py stats7 --floor 50