Integrals resist.
Watch a walker solve them.
Most interesting probability distributions cannot be integrated, inverted, or drawn from directly — we only know their shape up to an unknown constant. MCMC's answer is strange and beautiful: build a random walk whose long-run habit is the distribution itself, then let it wander. Every idea here — Monte Carlo error, stationarity, the Metropolis rule, autocorrelation, gradients — runs live in your browser.
Replace the integral with an average
Before chains, the simpler trick. Any integral is an expectation, and any expectation is approximated by an average of random draws. Throw darts at a square, count how many land in the circle, and you have π — never once having integrated anything. The price is error, and the error has a famous rate.
Watch the funnel narrow. To gain one more decimal place you need 100× more darts — that is what 1/√N costs. But notice what is not in that rate: the dimension. A grid needs 10d points to cover d dimensions; random averaging needs the same N whether d is 2 or 2 000. That immunity is why Monte Carlo runs modern statistics — and it is also why the next problem matters so much: how do you draw xi from π at all, when π is a posterior you can only evaluate up to a constant?
A walk that forgets, and a habit it cannot break
A Markov chain is a walker with amnesia: where it goes next depends only on where it is now, never on how it got there. Run one long enough and something remarkable happens — the fraction of time spent in each state stops depending on where it started. That limiting habit is the stationary distribution π, and MCMC is the art of running this backwards: pick the π you want, then design the walk.
Three conditions buy you that guarantee: the chain must be able to reach everywhere (irreducible), must not march in lockstep cycles (aperiodic), and must leave π alone once it arrives (stationary). “Two islands” shows the realistic version of the first failure: the bridge exists, but it is crossed about once in a thousand steps, so the walker can spend tens of thousands of steps reporting a confident, wrong answer about a world it has only seen half of. “Near-periodic” shows the second: the walker orbits in a near-lockstep cycle, and its running average keeps sloshing instead of settling. Both failures reappear — disguised, harder to see — in every real sampler in § 04. The knob that governs the wait is |λ₂|: push laziness up and watch the mixing time explode while the destination never changes.
Six lines of code that changed statistics
Here is the whole algorithm. From where you stand, propose a nearby point. If it is more probable, go. If it is less probable, still go — but only with probability equal to the ratio. That single asymmetry is enough to force the walk's long-run habit to be exactly π, and the unknown normalizing constant cancels in the ratio, so you never need it.
Now break it on purpose. Drag σ down to 0.05: the walker accepts almost everything — and goes nowhere, tracing a fuzzy blob that will take a million steps to find the other modes. Drag σ up to 6: nearly every proposal lands in the void and is rejected, so the trace becomes a staircase of long flat runs. Both extremes have terrible effective sample size. The sweet spot is roughly 25–45% acceptance — theory pins the optimum at 0.234 for high-dimensional random-walk proposals. The tragedy of the “Ring” target is that no single σ works well: the distribution's shape, not your tuning, is the enemy. That is § 05.
The chain always answers. Is it telling the truth?
MCMC never crashes and never warns you. A badly mixing chain returns smooth, confident, completely wrong numbers. So we run several chains from deliberately scattered starts and ask two questions: have they forgotten where they began (discard the burn-in), and do they now agree with each other? Below, four chains hunt a two-humped target.
Select “σ far too small” and watch the pathology that fools people: each trace looks like a lovely smooth curve, the autocorrelation bars refuse to decay, the four chains sit in four different places — and R̂ climbs past 10 while ESS collapses into the twenties. Smoothness in a trace is not a virtue; you want the ugly, dense “hairy caterpillar” that the well-tuned setting produces.
Then try “σ far too large” and read the numbers honestly: acceptance falls off a cliff — under 5% — and the trace turns into a staircase of long flat runs, yet R̂ stays close to 1 and ESS, though it drops several-fold, never collapses the way it does for tiny steps. In one dimension, over-stepping is merely wasteful — the rejected proposals cost you a constant factor, and the moves that do land are nearly independent. The reason practitioners fear large steps is dimension: acceptance decays exponentially as d grows, and what is wasteful in 1-D becomes fatal in 100-D. Meanwhile the deepest trap is visible in every setting here — with well-separated modes a chain can be perfectly converged within its own hump and never learn the other one exists. R̂ across dispersed starts is the cheapest defense we have.
Stop guessing. Use the shape.
A random-walk proposal is blind — it steps the same distance in every direction, so a narrow, correlated ridge forces it to shuffle. Two escapes. Gibbs updates one coordinate at a time, drawing exactly from its conditional: every move is accepted, but every move is axis-aligned. Hamiltonian Monte Carlo gives the walker momentum and lets the gradient of log π curve its path, sliding along the ridge in a single leap. Same target, same budget, below.
Gibbs—
Hamiltonian MC—
Push ρ to 0.99 and the verdict is brutal: the random walk's cloud collapses onto the ridge and crawls; Gibbs does better but still zig-zags in tiny axis-aligned staircases, because moving along a 45° ridge one coordinate at a time is like climbing stairs made for someone else; HMC's trajectories run down the length of the ridge and its ESS stays an order of magnitude ahead. This is why Stan, PyMC and NumPyro are built on HMC and its self-tuning cousin NUTS. The cost is real — HMC needs the gradient of log π, so your model must be differentiable — but when you have it, geometry beats guessing every time. Now turn ρ back to 0 and watch the ranking collapse: with the axes independent, Gibbs is drawing exactly independent samples and wins outright, while the random walk and HMC land within a factor of two of each other. On an easy target, sophistication buys nothing — the machinery only pays for itself when the geometry is hostile.
Ready to drive? The Sampler Lab → races all four samplers on targets you choose, and the Density Sandbox → lets you build your own distribution by hand and watch a chain try to map it.
Now you run the numbers
Five problems, each needing one idea from above and arithmetic you can do on paper. Hints reveal one step at a time — try before you peek, then check yourself against the simulators.
1 · The price of a decimal place
Your Monte Carlo estimate of π has a standard error of 0.05 after 1 000 darts. How many darts do you need to reach a standard error of 0.001 — and how long does that take at 20 000 darts per second?
σ/√N, so shrinking it by a factor k costs k² times as many samples.k = 0.05/0.001 = 50, so N = 1000 × 50² .N = 2 500 000 darts — about 125 seconds. Note the asymmetry: the first two decimals were nearly free, the third cost two minutes, and a fourth would cost 3½ hours. This is why MCMC papers report effective sample sizes in the hundreds, not the millions: past a point, precision is not worth the electricity.2 · Does the constant really cancel?
A posterior is π(θ) = p(θ)L(θ)/Z where Z = ∫p(θ)L(θ)dθ is a horrible integral you cannot compute. Show that the Metropolis acceptance probability never needs Z, and compute α for a proposal with p(y)L(y) = 0.030 from a state with p(x)L(x) = 0.075.
π(y)/π(x) = [p(y)L(y)/Z] / [p(x)L(x)/Z].Z in the numerator and denominator are the same number, so they divide out — leaving only unnormalized densities you can actually evaluate.α = min(1, 0.030/0.075) = 0.4. The move is accepted 40% of the time. This cancellation is the entire reason MCMC exists: we sample from a distribution we can never write down. It also means α is unchanged if you evaluate log-densities and exponentiate the difference — which is what every real implementation does, to avoid underflow.3 · Detailed balance by hand
A two-state chain has P(A→B) = 0.3 and P(B→A) = 0.1 (the rest are self-loops). Find the stationary distribution π, and verify it satisfies detailed balance π(A)P(A→B) = π(B)P(B→A).
π(A)·0.3 = π(B)·0.1, together with π(A) + π(B) = 1.π(B) = 3π(A). Substitute into the second: π(A) + 3π(A) = 1.π = (0.25, 0.75). Check: 0.25 × 0.3 = 0.075 = 0.75 × 0.1 ✓. The chain is reversible — a film of it run backwards has the same statistics. Metropolis–Hastings is engineered to satisfy exactly this equation for your chosen π, which is why its acceptance rule looks the way it does. Sticky states (large self-loops) do not change π at all — only how long you wait for it, as § 02 shows.4 · How much is a correlated chain worth?
A chain of 40 000 draws has lag-1 autocorrelation ρ = 0.95, decaying geometrically (ρk = 0.95k). What is its effective sample size — and what standard error does that imply for a parameter with posterior sd 2.0?
ESS = N / (1 + 2Σρₖ). For a geometric series, Σ_{k≥1} ρᵏ = ρ/(1−ρ).ρ/(1−ρ) = 0.95/0.05 = 19, so the integrated autocorrelation time is τ = 1 + 2(19) = 39.ESS = 40 000/39 ≈ 1 026 — your 40 000 draws are worth about a thousand. The Monte Carlo standard error is 2.0/√1026 ≈ 0.062, not the 2.0/√40000 = 0.01 you would have wrongly claimed. Reporting the naive figure overstates your precision six-fold; that is the single most common error in applied MCMC. Confirm the arithmetic in § 04 — the τ readout is exactly this number.5 · Why the ridge defeats the random walk
A 2-D Gaussian target has standard deviations 1.0 and 0.02 along its principal axes. Roughly how many random-walk steps are needed to traverse the long axis once, and why does that scaling get worse in higher dimensions?
σ ≈ 0.02.σ√T after T steps (it diffuses, it does not travel). Set σ√T = 1.0.T = (1.0/0.02)² = 2 500 steps for a single traverse — so getting a handful of independent samples costs tens of thousands of iterations. The cost goes as the squared condition number, and in d dimensions the optimal step shrinks further like d−1/2, compounding the problem. HMC's trajectories move ballistically rather than diffusively — distance grows like T, not √T — turning that 2 500 into roughly 50. Set ρ = 0.98 in § 05 and compare the three ESS readouts to see it happen.