Metropolis–Hastings Algorithm
The Metropolis–Hastings algorithm is the workhorse of Markov-chain Monte Carlo. Its purpose is to generate a sequence of configurations distributed, in the long run, according to a target probability distribution that is typically known only up to an unknown normalizing constant. In equilibrium statistical mechanics the target is the canonical Boltzmann distribution , whose normalization is the partition function — a quantity that is generically intractable. Metropolis–Hastings sidesteps entirely because the algorithm depends on only through ratios. The construction has two ingredients. A proposal mechanism suggests a candidate state; an accept/reject step then corrects the proposal so that the resulting transition kernel satisfies detailed balance with respect to . Detailed balance — the pairwise flow condition owned by the detailed-balance article — is a sufficient condition making stationary; the genius of the acceptance rule is that it enforces this condition using only the ratio , in which cancels identically. The Monte-Carlo framework into which this rule slots — importance sampling, the estimator, the error law — is owned by the monte-carlo-method article and recalled here by name; this article owns the algorithm itself. The single most important structural fact is that the acceptance rule is not arbitrary: it is the largest acceptance probability consistent with detailed balance, and Peskun's theorem shows this maximizes sampling efficiency at fixed proposal. The original Metropolis (1953) rule is the symmetric special case; Hastings (1970) extended it to arbitrary, possibly asymmetric proposals by inserting a correction factor. The chief practical limitation is correlation between successive samples: near a continuous phase transition the integrated autocorrelation time diverges (critical slowing down), which is exactly the failure that cluster algorithms were invented to defeat.
- Metropolis–Hastings (MH) builds a Markov chain whose unique stationary distribution is a prescribed target , allowing sampling from even when its normalization is unknown.
- Each step proposes from a proposal density and accepts it with probability .
- The acceptance rule enforces detailed balance, so together with ergodicity the chain converges to — and only ratios appear, so cancels.
- The original Metropolis (1953) rule is the symmetric special case , giving ; Hastings (1970) added the proposal-ratio correction for asymmetric proposals.
- is the largest acceptance consistent with detailed balance (Peskun), so it mixes fastest at fixed proposal; efficiency is set by the autocorrelation time and the acceptance ratio.
- Key idea: choose any proposal you like; accepting with forces detailed balance for , so the sampled distribution is regardless of the proposal — the proposal affects only efficiency, never correctness.
Choose any proposal ; then accepting with forces the chain to obey detailed balance for — so the sampled distribution is regardless of the proposal, which affects only efficiency, not correctness.
Where this lives today
Single-spin Metropolis sampling remains the reference method for measuring magnetization, susceptibility and transition temperatures in lattice spin models, and it is the accept/reject engine inside Hybrid (Hamiltonian) Monte Carlo used in lattice QCD, where molecular-dynamics trajectories serve as elaborate proposals and the MH step corrects for integration error. In Bayesian statistics and probabilistic machine learning, Metropolis–Hastings (and its gradient-informed descendant MALA, with optimal acceptance ) samples posteriors known only up to the evidence — the same -free setting as the Boltzmann distribution. The Roberts–Gelman–Gilks result that random-walk Metropolis is optimally tuned at acceptance in high dimension is a daily rule of thumb for practitioners. Where local MH stalls — near critical points, where — cluster algorithms take over.
The physical picture
Imagine exploring a landscape whose height is . You repeatedly propose a step. Downhill steps (toward higher probability) are always taken; uphill steps are taken only sometimes, with a probability that decreases the steeper the climb. This biased random walk spends time in each region in exact proportion to , so a histogram of where you have been reproduces the target distribution. The acceptance curve is the whole rule in one picture: a flat plateau at for downhill moves (), then an exponential roll-off for uphill moves. The genius is that only the ratio enters. The unknown normalization cancels identically — you never need to know how probable a state is in absolute terms, only how it compares to its neighbour. This is what makes Boltzmann sampling feasible despite being uncomputable, and it is why the same algorithm samples Bayesian posteriors (known only up to the evidence) without change. Two features often confuse newcomers. First, rejection is not wasted effort: staying put is how the chain assigns extra weight to high-probability states, so a rejected proposal means the current state is counted again in the average. Second, detailed balance is a bookkeeping device — it guarantees that in steady state the probability current from to exactly cancels the reverse current for every pair, which is a stronger (and more convenient) condition than mere stationarity. The detailed-balance article owns why pairwise balance implies stationarity; here we use it as a lemma and build the acceptance rule on top of it.
The core equations
The design target is detailed balance with respect to : for every pair of states the forward probability flux equals the reverse flux. This is a sufficient (not necessary) condition for to be stationary, and it is the condition the acceptance rule is built to satisfy.
where: — target stationary distribution (e.g. Boltzmann ); — transition probability of the constructed Markov chain. The kernel factorizes into a proposal and an acceptance. Whatever probability is not spent on accepted moves is assigned to staying put — this is where rejected proposals go, and it is what makes the chain re-count the current state.
where: — proposal density; — acceptance probability, . The Metropolis–Hastings acceptance probability is the rule that makes (2) satisfy (1). The Hastings factor corrects for any asymmetry in the proposal; when the proposal is symmetric it drops out.
where: — target ratio ( cancels); — Hastings proposal-ratio correcting for asymmetry. For Boltzmann sampling with a symmetric proposal, (3) collapses to the celebrated 1953 rule that depends only on the energy difference.
where: ; — energy of configuration ; . Efficiency is governed by autocorrelation. The variance of an estimate scales with the integrated autocorrelation time; near a critical point this diverges as a power of the correlation length — critical slowing down.
where: — normalized autocorrelation of observable at lag ; — correlation length; — dynamic exponent (local Metropolis on 2D Ising: ); — correlation-length exponent.
This derivation shows that the form is not a lucky guess but the optimal acceptance rule: it is the unique largest acceptance probability that satisfies detailed balance, and by Peskun's theorem the largest acceptance minimizes the asymptotic variance of Monte-Carlo estimates. We recall the detailed-balance condition (owned by the detailed-balance article) as our lemma and solve it for , keeping the acceptance as high as possible so the chain mixes fastest.
Step 1. Impose detailed balance on the factorized kernel. Substituting into :
Why: the flux of accepted-and-proposed transitions must balance in each direction — this is the detailed-balance lemma applied to the constructed chain.
Step 2. Solve for the ratio of acceptances. Define ; then
Why: any pair whose ratio equals satisfies detailed balance — the condition fixes only the ratio, not the individual values.
Step 3. Maximize the acceptance subject to . To decorrelate as fast as possible we want as large as the constraint allows. If set and ; if set and . Why: pushing whichever acceptance can be up to leaves the other determined by the ratio and never exceeds the bound.
Step 4. Both cases collapse to a single formula:
Why this is optimal: Peskun (1973) proved that among all acceptance functions satisfying detailed balance, dominates — it gives the smallest asymptotic variance. Barker's alternative also satisfies detailed balance but is provably less efficient. Verified: satisfies detailed balance symbolically for both orderings, and Barker's rule is confirmed valid-but-smaller, in verify_aq-sm-metropolis-hastings-algorithm.py.
Go deeper · Derivation B · 1 minSingle-spin Metropolis update for the Ising model
The point of this derivation is to make the abstract rule concrete and to expose why Metropolis is so cheap on lattice models: the acceptance depends only on a local energy change involving a spin and its neighbours, and on a square lattice only five distinct values of ever occur, so the Boltzmann factors can be precomputed. This locality is the source of the algorithm's -per-update efficiency and its dominance in critical-phenomena simulation.
Step 1. Local energy change. For with , propose flipping spin : . Only bonds touching site change, so
Why local: the flip reverses the sign of every bond at site and nothing else, so the global energy sum reduces to a neighbour sum.
Step 2. Acceptance. The proposal (pick a spin uniformly) is symmetric, so the Hastings factor is and
Step 3. Enumerate the possibilities. On the square lattice ( neighbours) , so . Why this matters: only five Boltzmann factors ever occur; precomputing them makes each update , independent of system size. Verified: the five allowed values and the symmetric-proposal reduction to are checked in verify_aq-sm-metropolis-hastings-algorithm.py.
Limiting cases
| Case | Result | Meaning |
|---|---|---|
| Symmetric proposal (original Metropolis) | makes the proposal ratio drop out — the famous 1953 rule. | |
| Heat-bath / Barker limit | Barker's alternative also satisfies detailed balance; for a single-spin flip it becomes . Provably less efficient than Metropolis (Peskun). | |
| High temperature / flat target | All moves accepted; the chain reduces to the proposal random walk — fast mixing, little structure. | |
| Low temperature / sharp target | Only energy-lowering moves accepted; greedy descent freezes in local minima — needs annealing or parallel tempering. | |
| Critical region | (2D Ising) | Local updates suffer critical slowing down; cluster algorithms restructure the spectrum to drive . |
Worked examples
Example 1 — Two-level system: sampling and verifying detailed balance. Take two states (energy ) and (energy ) with . Compute the target ratio and the Metropolis acceptances, then check detailed balance numerically.
Step 1. Target ratio. The Boltzmann weights give . This is what a long chain must reproduce.
Step 2. Acceptances (symmetric proposal, each way). Uphill : . Downhill : .
Step 3. Verify detailed balance. The flux is ; the flux is . Using , both equal — balanced exactly. A simulated chain of steps visits state a fraction of the time, matching within Monte-Carlo error.
Example 2 — Hastings correction restores detailed balance for a biased proposal. Suppose the proposal favours state over state : , (asymmetric). Show the bare Metropolis rule is wrong and the Hastings factor fixes it, at .
Step 1. Bare (wrong) acceptance. Using ignores the proposal bias; the resulting stationary ratio is . The chain samples the wrong distribution.
Step 2. Hastings acceptance. Insert the proposal ratio: , so and .
Step 3. Verify. Now the flux ratio is , so detailed balance holds and the chain samples correctly. The Hastings factor is not optional for asymmetric proposals — omitting it gives a stationary ratio instead of the correct .
Origins · 1 minnicholas metropolis and how this was discovered
Going further
References. Pathria & Beale, Statistical Mechanics, 3rd ed., Ch. 16 (Computer Simulations) · Kardar, Statistical Physics of Fields, Ch. 8 (Monte Carlo methods) · Sethna, Statistical Mechanics: Entropy, Order Parameters, and Complexity, Ch. 8 · Newman & Barkema, Monte Carlo Methods in Statistical Physics, Ch. 2–3 · Metropolis, Rosenbluth, Rosenbluth, Teller & Teller, J. Chem. Phys. 21, 1087 (1953) · Hastings, Biometrika 57, 97 (1970) · Peskun, Biometrika 60, 607 (1973) · Roberts, Gelman & Gilks, Ann. Appl. Prob. 7, 110 (1997).
Provenance. A verifier should: (1) confirm satisfies detailed balance for both orderings, and that Barker's rule is valid but smaller (Peskun); (2) check the Ising single-spin and the five allowed square-lattice values; (3) verify the two-level sampling and the Hastings correction for an asymmetric proposal (this article's verify script); (4) the quoted (2D Ising local dynamics) and optimal acceptances / are standard literature values. Detailed balance itself is owned by the detailed-balance article and the MC framework by the monte-carlo-method article.
Builds on: Markov Processes and the Markov Property · Detailed Balance and Microscopic Reversibility · The Master Equation · Chapman–Kolmogorov Equation. Leads to: Monte Carlo Method · Cluster Algorithms and Critical Slowing Down · Thermostats and Ensemble Control in Molecular Dynamics · Molecular Dynamics Simulation.
What exactly is the difference between "Metropolis" and "Metropolis–Hastings"?
The 1953 Metropolis rule assumes a symmetric proposal, , so the acceptance is just . Hastings (1970) generalized this to any proposal by inserting the ratio , giving . Metropolis is the symmetric special case of Metropolis–Hastings. The generalization matters whenever the proposal is deliberately biased — e.g. particle insertion/deletion in the grand-canonical ensemble.
Is detailed balance necessary, or just convenient?
Just sufficient, not necessary. The necessary-and-sufficient condition for to be stationary is global balance, — total flow into each state equals total flow out. Detailed balance enforces this pairwise, which is stronger but far easier to arrange (it fixes the acceptance ratio locally). Non-reversible samplers satisfy global balance without detailed balance and can mix faster, at the cost of a harder design. The detailed-balance article owns the distinction; here it is the lemma the acceptance rule is built on.
Why not just always accept the proposed move?
Because always moving would under-sample the high-probability states. Rejection is the mechanism by which the chain lingers in probable regions: a state with high tends to reject proposals to lower- neighbours, so the chain sits there longer and accumulates more weight. Removing rejection (or, equivalently, failing to re-count the current state after a rejection) breaks the -weighting and biases every estimate.
How do I choose the proposal step size?
Tune it to a target acceptance rate. Too-bold proposals are almost always rejected (the chain stalls); too-timid proposals are almost always accepted but move a tiny distance (slow exploration). The efficiency measure is the expected squared jump distance , maximized at intermediate step size. In high dimension the universal optimum for random-walk Metropolis is acceptance (Roberts–Gelman–Gilks 1997); for the gradient-informed MALA variant it is . In practice, tune to acceptance –.
Does Metropolis–Hastings give real physical dynamics?
No — the "time" of an MH chain is fictitious, a sequence of accept/reject moves chosen to sample the correct statics. With single-spin flips it happens to resemble Glauber relaxation, but in general it carries no dynamical information. Genuine time-correlation functions and transport coefficients require molecular dynamics (owned by the molecular-dynamics article) or a physically rated kinetic Monte Carlo. MH guarantees the equilibrium distribution, nothing about the route to it.
What is critical slowing down and why does it break local MH?
Near a continuous transition the correlation length diverges. A local update can only rearrange an ordered domain of size by a random walk of single flips across it, which takes sweeps, so the integrated autocorrelation time grows as with in 2D Ising. Since the effective sample count is , precision collapses right where the interesting physics is. Cluster algorithms flip whole correlated domains in one move, restructuring the transition operator's spectrum so .
Can I use Metropolis–Hastings for continuous-parameter Bayesian inference?
Yes — this is one of its biggest modern uses. Set , the unnormalized posterior; the evidence (normalization) plays the role of and cancels. Propose from a Gaussian random walk (or a gradient-informed MALA/HMC proposal), accept with the MH rule, and the chain samples the posterior. The same autocorrelation and acceptance-tuning caveats apply; convergence diagnostics (multiple chains, ) replace the physicist's thermalization checks.