Core ML1953intermediate11 min read

Equation of State Calculations by Fast Computing Machines

حسابات معادلة الحالة باستخدام الحواسيب السريعة

Metropolis, N. · Rosenbluth, A. W. · Rosenbluth, M. N. · Teller, A. H. · Teller, E. — The Journal of Chemical Physics

The problem

In 1953, physicists needed to compute thermodynamic properties — like pressure and energy — of systems with hundreds of interacting molecules. Exact calculation requires summing over an astronomically large number of configurations (all possible positions of all particles). Even the fastest computers of the era could not evaluate this sum directly. Simple — configurations uniformly at random — wastes almost all its effort on high-energy states that contribute negligibly to the physical averages.

The contribution

A "modified Monte Carlo" method that samples configurations not uniformly but in proportion to the exp(−E/kT). Instead of evaluating all states, it constructs a random walk through configuration space: propose a random move, accept it if it lowers energy, and if it raises energy accept it with probability exp(−ΔE/kT). This converges to the equilibrium , so time-averages along the walk equal the desired thermodynamic averages. The method was implemented on the MANIAC computer at Los Alamos for a system of 224 rigid disks.

The impact

This paper created Markov chain Monte Carlo (MCMC), arguably the most influential computational of the 20th century. Hastings generalized the acceptance rule in 1970. Gibbs sampling (1984) became a special case. Simulated annealing (1983) adapted the idea for . Today MCMC underpins Bayesian statistics, computational physics, , computational biology, and finance — anywhere you need to sample from a complex distribution you cannot evaluate in closed form.

Imagine a blindfolded traveler on a mountain range who wants to map where the valleys are. She can't see the landscape, but she can feel the altitude under her feet.

Simple Monte Carlo is like dropping her at random spots by helicopter: most landings hit barren peaks, and she learns almost nothing about the valleys where all the interesting physics happens.

The Metropolis method gives her a smarter strategy: take one step in a random direction. If you go downhill, always walk. If uphill, flip a weighted coin — the steeper the climb, the less likely you walk. Over thousands of steps she drifts naturally into the valleys, spending time in each valley in exact proportion to how deep it is. She never sees the full map, yet her travel diary is the map.

The problem: summing over an impossible number of states

A gas of N interacting particles at T has thermodynamic properties determined by the — a sum over every possible arrangement of all N particles. Each arrangement has an energy E, and its contribution is weighted by the Boltzmann factor exp⁡(−E/kT)\exp(-E / kT).

For a system of just 100 particles, the number of possible configurations is effectively infinite. Direct computation is hopeless. By 1953 physicists had been using Monte Carlo integration: pick random configurations, compute their energies, and average. But uniform random sampling wastes nearly all its effort on high-energy configurations whose Boltzmann weight is essentially zero. It's like searching for needles in a haystack by examining random straws.

⟨A⟩=∑statesA(r) e−E(r)/kT∑statese−E(r)/kT\langle A \rangle = \frac{\sum_{\text{states}} A(\mathbf{r}) \, e^{-E(\mathbf{r})/kT}} {\sum_{\text{states}} e^{-E(\mathbf{r})/kT}}
Thermodynamic average — what we want to compute — The average of any property A is a weighted sum over all configurations r, where the weight is the Boltzmann factor. The denominator (partition function) is itself an intractable sum.
Open in Lab
Compare uniform random sampling (left) with Boltzmann-weighted sampling (right). Notice how uniform sampling wastes most effort on high-energy regions.
The demo wakes as you arrive…

The insight: let the samples find the important regions

The key idea is with a random walk. Instead of choosing configurations uniformly and then weighting them, generate configurations that are already distributed according to the Boltzmann distribution. Then the average of any property A is just a simple unweighted mean of the values you see along the walk.

But how do you generate samples from the Boltzmann distribution when you can't even compute the partition function? This is the chicken-and-egg problem the Metropolis algorithm solves: you don't need to know the — only ratios of probabilities, which are ratios of Boltzmann factors, and those simplify to exp⁡(−ΔE/kT)\exp(-\Delta E / kT).

The algorithm: propose, evaluate, accept or reject

The Metropolis algorithm is strikingly simple. Start from any configuration. Then repeat:

  1. Propose — pick a particle at random and move it by a small random displacement.
  2. Evaluate — compute the energy change ΔE caused by the move.
  3. Decide — if ΔE ≤ 0 (energy went down or stayed the same), accept the move. If ΔE > 0 (energy went up), accept with probability exp⁡(−ΔE/kT)\exp(-\Delta E / kT) — draw a uniform random number u ∈ [0, 1] and accept if u<exp⁡(−ΔE/kT)u < \exp(-\Delta E / kT).

That's the entire algorithm. The accepted configurations form a Markov chain whose is the Boltzmann distribution. After a burn-in period, every configuration along the chain is a sample from the target distribution.

α=min⁡ ⁣(1,  e−ΔE/kT)\alpha = \min\!\Big(1,\; e^{-\Delta E / kT}\Big)
Metropolis acceptance probability — If the move lowers energy (ΔE < 0), the exponent is positive so α = 1 — always accept. If it raises energy, the probability of acceptance shrinks exponentially with the energy increase, modulated by temperature.
Open in Lab
Click each step to see what happens at that stage of the algorithm.
The demo wakes as you arrive…

Think of the acceptance rule as a doorman at a club. If you're bringing the energy down (the party gets better), you always get in. If you'd raise the energy (make it worse), you might get in — the doorman flips a weighted coin, and the heavier the energy cost the less likely you pass. At high temperature the coin is nearly fair (the doorman is lenient), so the walk explores freely. At low temperature the coin is heavily loaded against uphill moves, so the walk hugs the valleys.

Open in Lab
Propose moves and watch the accept/reject decision. Adjust temperature to see how it affects exploration.
The demo wakes as you arrive…

Why it works: detailed balance

The magic lies in a property called . Imagine traffic flowing between two cities. If in the long run the same number of cars flow from A to B as from B to A, neither city gains or loses population — the system is in equilibrium.

Detailed balance says exactly this for the Markov chain: for any two states i and j, the flow of probability from i to j equals the flow from j to i. Formally:

π(i) T(i→j)=π(j) T(j→i)\pi(i) \, T(i \to j) = \pi(j) \, T(j \to i)

where π is the target distribution and T is the . When this holds, π is the stationary distribution of the chain. The Metropolis acceptance rule is designed to satisfy this equation when π is the Boltzmann distribution. You can verify: the ratio T(i→j)/T(j→i)T(i \to j) / T(j \to i) equals π(j)/π(i)\pi(j)/\pi(i) by construction.

Open in Lab
Watch probability flow between two states. Detailed balance ensures the flows equalize, keeping the distribution stationary.
The demo wakes as you arrive…

Temperature: the exploration dial

Temperature T plays a crucial role in balancing and :

  • At high temperature, exp⁡(−ΔE/kT)≈1\exp(-\Delta E / kT) \approx 1 for most moves, so nearly everything is accepted. The walk explores broadly but doesn't concentrate on any particular region — like a heated gas where particles fly everywhere.
  • At low temperature, exp⁡(−ΔE/kT)≈0\exp(-\Delta E / kT) \approx 0 for uphill moves, so only downhill moves are accepted. The walk becomes trapped in the nearest energy minimum — like a frozen solid where particles barely vibrate.
  • At just right temperature, the walk explores enough to find deep valleys but lingers in them long enough to sample them well.

This temperature knob inspired simulated annealing (Kirkpatrick et al., 1983): start at high temperature to explore, then slowly cool to concentrate on the — mimicking the physical annealing of metals.

Open in Lab
Drag the temperature slider to see how the random walk changes its behavior.
The demo wakes as you arrive…

Hastings' generalization (1970): asymmetric proposals

The original Metropolis algorithm assumed the proposal distribution is symmetric: the probability of proposing a move from state i to state j equals the probability of proposing the reverse. In 1970, W. K. Hastings generalized the to handle asymmetric proposals:

α(i→j)=min⁡ ⁣(1,  π(j) q(i∣j)π(i) q(j∣i))\alpha(i \to j) = \min\!\left(1,\; \frac{\pi(j)\, q(i \mid j)}{\pi(i)\, q(j \mid i)} \right)

where q(j∣i)q(j \mid i) is the proposal probability. When the proposal is symmetric — q(j∣i)=q(i∣j)q(j \mid i) = q(i \mid j) — the q terms cancel and you recover the original Metropolis rule. This generalization opened MCMC to a vast range of proposal strategies and made the algorithm applicable far beyond physics.

αMH(i→j)=min⁡ ⁣(1,  π(j)  q(i∣j)π(i)  q(j∣i))\alpha_{\text{MH}}(i \to j) = \min\!\left(1,\; \frac{\pi(j)\; q(i \mid j)}{\pi(i)\; q(j \mid i)}\right)
Metropolis-Hastings acceptance probability — the general form — The ratio π(j)/π(i) measures how much the target "prefers" the new state. The ratio q(i|j)/q(j|i) corrects for any asymmetry in how proposals are generated. Together they ensure detailed balance regardless of the proposal shape.

The same idea in code

Metropolis-Hastings sampler, completepython

Simplified to show the idea — not the real implementation.

import numpy as np

def metropolis_hastings(log_prob, x0, proposal_std, n_samples, burn_in=1000):
    """
    Sample from a distribution known up to a constant.
    log_prob: function returning log π(x) (unnormalized is fine)
    x0: starting point
    proposal_std: standard deviation of Gaussian proposal
    """
    x = x0
    samples = []
    log_p = log_prob(x)

    for i in range(n_samples + burn_in):
        # 1. PROPOSE: symmetric Gaussian step
        x_new = x + np.random.randn() * proposal_std

        # 2. EVALUATE: compute log acceptance ratio
        log_p_new = log_prob(x_new)
        log_alpha = log_p_new - log_p          # log(π(new)/π(old))

        # 3. DECIDE: accept or reject
        if np.log(np.random.rand()) < log_alpha:
            x = x_new                          # accept: move to new state
            log_p = log_p_new
        # else: reject — stay at x (implicit, nothing changes)

        if i >= burn_in:
            samples.append(x)

    return np.array(samples)

# Example: sample from a bimodal distribution
def bimodal_log_prob(x):
    """Log of a mixture of two Gaussians."""
    return np.log(0.3 * np.exp(-0.5*(x+3)**2)
                + 0.7 * np.exp(-0.5*(x-2)**2) + 1e-300)

samples = metropolis_hastings(bimodal_log_prob, x0=0.0,
                               proposal_std=1.5, n_samples=10000)
# samples is now ~10,000 draws from the bimodal distribution

Convergence: when can you trust the samples?

The Markov chain will eventually converge to the target distribution — this is guaranteed by (the chain can reach any state from any other state) and detailed balance. But "eventually" can be a long time.

Two practical concerns dominate:

  • Burn-in — the initial samples reflect the starting point, not the target distribution. Discard the first N samples (the "burn-in" period) to remove this bias.
  • Mixing — if the chain moves in tiny steps, consecutive samples are highly correlated and the chain takes a long time to "mix" (explore the full distribution). If steps are too large, most proposals are rejected and the chain barely moves. The proposal scale must be tuned: a common rule of thumb targets an acceptance rate of about 23–44% in high dimensions.
Open in Lab
Adjust the proposal scale and watch how the chain's acceptance rate and convergence change. Too small = slow mixing. Too large = high rejection.
The demo wakes as you arrive…

The original experiment: 224 hard disks on MANIAC

Metropolis and the Rosenbluths implemented the algorithm on the MANIAC computer at Los Alamos for a two-dimensional system of 224 rigid disks (hard spheres that can't overlap). Each "move" displaced one disk by a small random amount within a square of side 2α. If the new position caused disks to overlap, the move was rejected. Otherwise, it was always accepted (since all non-overlapping configurations have the same energy for hard spheres).

They ran the chain for hundreds of cycles (one cycle = 224 attempted moves, one per particle) and computed the equation of state — the relationship between pressure and density. Their results agreed with the theoretical four-term virial expansion at low density and revealed behavior at high density that no analytical method could predict.

Open in Lab
A simplified recreation of the original experiment. Press Play to watch disks rearrange via the Metropolis algorithm.
The demo wakes as you arrive…

Why it changed everything

  1. 1953

    Metropolis Algorithm

    The original paper. Symmetric random walk proposals for sampling from the Boltzmann distribution. Applied to hard disks on the MANIAC computer.

  2. 1970

    Hastings Generalization

    W. K. Hastings extended the acceptance rule to asymmetric proposal distributions, creating the general Metropolis-Hastings framework used today.

  3. 1983

    Simulated Annealing

    Kirkpatrick, Gelatt, and Vecchi adapted the Metropolis algorithm for combinatorial optimization by slowly decreasing temperature to find global minima.

  4. 1984

    Gibbs Sampling

    Geman & Geman introduced Gibbs sampling for image restoration — a special case of Metropolis-Hastings where proposals use conditional distributions and are always accepted.

  5. 1990

    MCMC Enters Statistics

    Gelfand and Smith's paper brought MCMC to mainstream Bayesian statistics, showing its power for posterior inference in complex hierarchical models.

  6. 2003

    "Top 10 Algorithms of the 20th Century"

    The Metropolis algorithm was named one of the top 10 algorithms of the 20th century by Computing in Science & Engineering — alongside FFT, PageRank's predecessor, and the simplex method.

  7. 2011

    NUTS (No-U-Turn Sampler)

    Hoffman and Gelman's adaptive Hamiltonian Monte Carlo variant automates tuning and powers modern probabilistic programming frameworks like Stan and PyMC.

The Metropolis algorithm is to sampling what is to optimization: a simple, universal workhorse that launched an entire field. Every modern MCMC variant — Hamiltonian Monte Carlo, slice sampling, reversible-jump MCMC — descends from the same core idea: propose, evaluate the ratio, accept or reject.

CitationMetropolis, N., Rosenbluth, A. W., Rosenbluth, M. N., Teller, A. H., Teller, E.. Equation of State Calculations by Fast Computing Machines. The Journal of Chemical Physics, 1953.

Terms in this paper