Sign in

Monte carlo methods

Estimating integrals and drawing samples with random numbers: plain Monte Carlo, importance sampling, rejection sampling and Metropolis-Hastings.

Overview

Many quantities are averages in disguise: an integral is the average height of a function times the width of its range. So draw random points, evaluate the function and take the mean. The answer is noisy, but the noise shrinks in a known way as you draw more, and it does not get worse in high dimensions the way grids do. When you cannot sample from the distribution you care about, three tricks help. Importance sampling draws from an easier distribution and reweights. Rejection sampling draws from an easier one and throws some draws away. Markov chain Monte Carlo, or MCMC, takes a random walk that visits each region in proportion to its probability.

A short history

Stanislaw Ulam and John von Neumann developed the method at Los Alamos in the 1940s to study neutron diffusion, and Nicholas Metropolis named it after the casino. Metropolis and Ulam published the idea in 1949. In 1953 Metropolis and colleagues gave the first Markov chain sampler, which W. K. Hastings generalised in 1970. These samplers later made Bayesian statistics practical for models with no closed-form answer.

How it works

  1. Write the quantity you want as an expectation: the average of some function under some distribution.
  2. Plain Monte Carlo: draw nn samples, evaluate the function at each, and average. Report the standard error alongside the estimate.
  3. Importance sampling: draw from a proposal qq that you can sample, and weight each draw by target density over proposal density.
  4. Rejection sampling: draw from qq and keep each draw with probability equal to the target divided by a scaled proposal that sits above it everywhere.
  5. Metropolis-Hastings: from the current point propose a small random move. Accept it if the target is higher there, and otherwise accept with probability equal to the ratio of target values.
  6. Discard the first steps of the chain (the burn-in), then treat the remaining points as correlated samples of the target.
  7. Check quality with the effective sample size, which says how many independent draws your weighted or correlated samples are worth.

Watch out for

  • The error falls like 1/n1 / \sqrt{n}. One more correct digit costs a hundred times more samples.
  • Importance sampling fails quietly when the proposal has lighter tails than the target. A few huge weights then carry the estimate, and the effective sample size collapses.
  • Rejection sampling needs a bound that holds everywhere, and its acceptance rate drops quickly as the dimension grows.
  • Metropolis-Hastings samples are correlated, so 20000 steps may be worth only a few hundred independent draws. A proposal scale that is too small or too large makes this worse.
  • A chain started far from the bulk of the target, or one that never crosses between separated peaks, can look settled while being wrong. Run several chains from different starts.

Use cases

When to use it

Integrals with no closed form, especially in many dimensions, and sampling from a distribution known only up to a constant, which is the usual situation for a Bayesian posterior.

In industry

Finance
Banks price path-dependent options and estimate value at risk by simulating many market scenarios and averaging the outcomes.
Physics and engineering
Particle transport codes simulate individual particles through matter to design reactor shielding and radiation therapy plans.
Computer graphics
Film renderers use path tracing, which averages random light paths per pixel to estimate the lighting integral.
Bayesian statistics
Tools such as Stan and PyMC draw posterior samples with Markov chain Monte Carlo when no formula for the posterior exists.

Choosing it: what must hold

  • A quantity that can be written as an expectation or integral over a distribution.
  • A way to draw samples from that distribution, or a density you can evaluate up to a constant for MCMC.
  • A compute budget for many samples: the error shrinks only with the square root of the sample count.
  • For MCMC, checks that the chain has converged and mixed before its samples are used.

When to choose something else

IfUse instead
The integral has a closed form or the problem has one or two dimensionsThe exact formula, or numerical quadrature
The prior is conjugate to the likelihoodBayesian inference in closed form
You need a fast approximate posterior for a very large modelVariational inference

Math foundations

  1. The Monte Carlo estimate

    Ep[f(X)]≈μ^n=1n∑i=1nf(xi),xi∼p\mathbb{E}_{p}[f(X)] \approx \hat{\mu}_n = \frac{1}{n}\sum_{i=1}^{n} f(x_i), \qquad x_i \sim p

    Replace an expectation by an average over samples. For an integral over [a,b][a, b], draw xix_i uniformly and multiply the average by b−ab - a. The law of large numbers says this converges.

  2. Its standard error

    se⁡(μ^n)=sn,s2=1n−1∑i=1n(f(xi)−μ^n)2\operatorname{se}(\hat{\mu}_n) = \frac{s}{\sqrt{n}}, \qquad s^{2} = \frac{1}{n - 1}\sum_{i=1}^{n} \big(f(x_i) - \hat{\mu}_n\big)^{2}

    The spread of the estimate, measured from the same samples. It depends on the number of samples and the variability of ff, not on the dimension of xx.

  3. Importance sampling

    Ep[f(X)]≈∑iwi f(xi)∑iwi,wi=p~(xi)q(xi),xi∼q\mathbb{E}_{p}[f(X)] \approx \frac{\sum_{i} w_i\,f(x_i)}{\sum_{i} w_i}, \qquad w_i = \frac{\tilde{p}(x_i)}{q(x_i)}, \qquad x_i \sim q

    Draws from qq are corrected by weights that say how much more or less likely each point is under the target. Dividing by the sum of weights means p~\tilde{p} only needs to be known up to a constant.

  4. Effective sample size of weights

    neff=(∑iwi)2∑iwi2n_{\text{eff}} = \frac{\left(\sum_{i} w_i\right)^{2}}{\sum_{i} w_i^{2}}

    Equal weights give neff=nn_{\text{eff}} = n. If one weight dominates, neffn_{\text{eff}} is close to 1 and the estimate rests on a single draw.

  5. Rejection sampling

    accept x∼q  with probability  p~(x)M q(x),p~(x)≤M q(x)  for all x\text{accept } x \sim q \ \text{ with probability } \ \frac{\tilde{p}(x)}{M\,q(x)}, \qquad \tilde{p}(x) \le M\,q(x) \ \text{ for all } x

    Accepted draws are exact samples of the target. The overall acceptance rate is the area under p~\tilde{p} divided by MM, so a loose bound wastes most proposals.

  6. Metropolis-Hastings acceptance

    α(x→x′)=min⁡ ⁣(1, p~(x′)p~(x))\alpha(x \to x') = \min\!\left(1,\ \frac{\tilde{p}(x')}{\tilde{p}(x)}\right)

    For a symmetric proposal such as a Gaussian step. Uphill moves are always taken and downhill moves sometimes, which makes the target the stationary distribution of the chain. Only a ratio appears, so the normalizing constant is never needed.

  7. Effective sample size of a chain

    neff=n1+2∑k=1∞ρkn_{\text{eff}} = \frac{n}{1 + 2\sum_{k=1}^{\infty} \rho_k}

    Positive autocorrelation between samples kk steps apart reduces the information in the chain. The template truncates the sum at the first lag where ρk\rho_k is not positive.

Symbols

ff
the function whose average is wanted
pp
the target distribution
p~\tilde{p}
the target density, possibly without its normalizing constant
qq
the proposal distribution, which is easy to sample from
xix_i
the ii-th sample
nn
the number of samples (n_samples in the config)
μ^n\hat{\mu}_n
the Monte Carlo estimate from nn samples
ss
the sample standard deviation of the values f(xi)f(x_i)
wiw_i
the importance weight of sample ii
MM
the constant with p~≤Mq\tilde{p} \le M q everywhere (bound in the code)
x, x′x,\ x'
the current point of the chain and the proposed point
α\alpha
the probability of accepting a proposed move
ρk\rho_k
the autocorrelation of the chain at lag kk
neffn_{\text{eff}}
the effective sample size

Worked by hand

Estimate π\pi by dropping points uniformly in the unit square and counting those inside the quarter circle of radius 1, whose area is π/4\pi / 4. Suppose 10 points are drawn and 8 fall inside.

π^=4×810=3.2\hat{\pi} = 4 \times \frac{8}{10} = 3.2
s≈40.8×0.2=1.6,se⁡=1.610≈0.51s \approx 4\sqrt{0.8 \times 0.2} = 1.6, \qquad \operatorname{se} = \frac{1.6}{\sqrt{10}} \approx 0.51
n≈(1.640.01)2≈27000  for a standard error of 0.01n \approx \left(\frac{1.64}{0.01}\right)^{2} \approx 27000 \ \text{ for a standard error of } 0.01

Ten points give 3.2, give or take about 0.5. Each point contributes 4 or 0, and that spread is about 1.64 at the true value, so two reliable decimal places already need roughly 27000 points.

Visual example

Loading the example.

Try this

  • With Metropolis-Hastings, drop the proposal width to 0.3: the chain stays in one hump and the estimate is badly off.
  • Switch to rejection sampling and widen the proposal. The envelope rises and the acceptance rate falls.
  • Use importance sampling with a width of 0.8 and read the effective sample size.

Code sample

import numpy as np
from impl import MonteCarlo
from config import MonteCarloConfig

mc = MonteCarlo(MonteCarloConfig(n_samples=20000, proposal_scale=2.5))
value, err = mc.integrate(lambda x: x**2, 0.0, 1.0)        # about 1/3, with its standard error

log_target = lambda x: float(-0.5 * ((x[0] - 3.0) / 2.0) ** 2)    # N(3, 2^2) up to a constant
samples, rate = mc.metropolis_hastings(log_target, x0=0.0)  # samples (20000, 1), mean near 3, std near 2
Read the implementation (133 lines)
"""Monte Carlo methods.

Plain Monte Carlo integration with a standard error, importance sampling, rejection sampling, and
random-walk Metropolis-Hastings MCMC. All four turn random draws into estimates of integrals or into samples
of a distribution known only up to a constant.
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import MonteCarloConfig
except ImportError:  # run from the template's own folder
    from config import MonteCarloConfig

class MonteCarlo:
    """Sampling-based estimators that share one seeded random generator (`self.rng`)."""

    def __init__(self, config: MonteCarloConfig | None = None) -> None:
        self.config = config or MonteCarloConfig()
        self.rng = np.random.default_rng(self.config.seed)

    def integrate(self, func, low: float, high: float) -> tuple[float, float]:
        """Estimate the integral of func over [low, high] from uniform draws.

        func takes and returns an array (n,). Returns (estimate, standard error of the estimate).
        """
        if not high > low:
            raise ValueError("high must be greater than low")
        n = self.config.n_samples
        values = (high - low) * np.asarray(func(self.rng.uniform(low, high, size=n)), dtype=float)
        return float(values.mean()), float(values.std(ddof=1) / math.sqrt(n)) if n > 1 else math.inf

    def estimate_pi(self) -> float:
        """4 times the share of uniform points in the unit square that fall inside the quarter circle."""
        points = self.rng.random((self.config.n_samples, 2))
        return float(4.0 * np.mean((points**2).sum(axis=1) <= 1.0))

    def importance_sampling(self, func, log_target, sample_proposal, log_proposal,
                            self_normalized: bool = True) -> tuple[float, float]:
        """Estimate E_target[func(x)] with draws from a different (proposal) distribution.

        func:            array (n, ...) -> array (n,), the quantity to average.
        log_target:      array -> array (n,), log density of the target; may lack its normalizing constant
                         when self_normalized is True.
        sample_proposal: (rng, n) -> array of n draws from the proposal.
        log_proposal:    array -> array (n,), log density of the proposal.
        Returns (estimate, effective sample size). An effective sample size far below n means the proposal
        is a poor match and the estimate rests on a handful of draws.
        """
        n = self.config.n_samples
        x = sample_proposal(self.rng, n)
        log_w = np.asarray(log_target(x), dtype=float) - np.asarray(log_proposal(x), dtype=float)
        values = np.asarray(func(x), dtype=float)
        if self_normalized:
            w = np.exp(log_w - log_w.max())
            estimate = float((w * values).sum() / w.sum())
        else:
            w = np.exp(log_w)
            estimate = float((w * values).mean())
        return estimate, float(w.sum() ** 2 / (w**2).sum())

    def rejection_sampling(self, target_pdf, sample_proposal, proposal_pdf, bound: float) -> tuple[np.ndarray, float]:
        """Exact samples of the target, using a proposal with target_pdf(x) <= bound * proposal_pdf(x) everywhere.

        target_pdf may be unnormalized. A draw x is kept with probability target_pdf(x) / (bound * proposal_pdf(x)).
        Returns (samples with n_samples entries along axis 0, acceptance rate).
        """
        if bound <= 0:
            raise ValueError("bound must be positive")
        n = self.config.n_samples
        kept, n_kept, n_tried = [], 0, 0
        while n_kept < n:
            x = sample_proposal(self.rng, n)
            ratio = np.asarray(target_pdf(x), dtype=float) / (bound * np.asarray(proposal_pdf(x), dtype=float))
            if np.any(ratio > 1.0 + 1e-9):
                raise ValueError("bound is too small: the target exceeds bound * proposal somewhere")
            accepted = x[self.rng.random(n) < ratio]
            kept.append(accepted)
            n_kept += len(accepted)
            n_tried += n
            if n_tried >= 1000 * n and n_kept == 0:
                raise ValueError("no proposal was accepted, check the densities and the bound")
        return np.concatenate(kept)[:n], n_kept / n_tried

    def metropolis_hastings(self, log_target, x0) -> tuple[np.ndarray, float]:
        """Random-walk Metropolis-Hastings.

        log_target: array (d,) -> float, log density up to an additive constant.
        x0:         starting point, scalar or array (d,).
        Returns (samples array (n_samples, d), acceptance rate over all steps including burn-in).
        Consecutive samples are correlated, so they carry less information than independent draws.
        """
        x = np.atleast_1d(np.asarray(x0, dtype=float)).copy()
        log_p = float(log_target(x))
        if not math.isfinite(log_p):
            raise ValueError("the starting point has zero target density")
        total = self.config.burn_in + self.config.n_samples
        steps = self.rng.normal(0.0, self.config.proposal_scale, size=(total, x.size))
        log_u = np.log(self.rng.random(total))
        samples = np.empty((self.config.n_samples, x.size))
        accepted = 0
        for t in range(total):
            candidate = x + steps[t]
            log_p_candidate = float(log_target(candidate))
            if log_u[t] < log_p_candidate - log_p:  # symmetric proposal: the ratio of targets decides
                x, log_p = candidate, log_p_candidate
                accepted += 1
            if t >= self.config.burn_in:
                samples[t - self.config.burn_in] = x
        return samples, accepted / total


def effective_sample_size(chain, max_lag: int = 1000) -> float:
    """Effective number of independent samples in a correlated 1-D chain, array (n,).

    n / (1 + 2 * sum of autocorrelations), with the sum cut at the first non-positive autocorrelation.
    """
    x = np.asarray(chain, dtype=float).ravel()
    n = x.size
    x = x - x.mean()
    var = float(np.dot(x, x) / n)
    if var == 0:
        return float(n)
    tau = 1.0
    for lag in range(1, min(max_lag, n - 1)):
        rho = float(np.dot(x[:-lag], x[lag:]) / (n * var))
        if rho <= 0:
            break
        tau += 2.0 * rho
    return n / tau
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Create MonteCarlo with the default config. Call estimate_pi, then integrate(np.sin, 0, np.pi) and compare the error with the reported standard error (the exact value is 2). Run metropolis_hastings on a standard normal log density, lambda x: -0.5 * float(x @ x), from x0 = 0, with proposal_scale 0.1, 2.4 and 50, and compare acceptance rates and effective_sample_size of the first column.

Check on learning

  1. A grid with 10 points per axis needs 10d10^{d} evaluations in dd dimensions. Why does the Monte Carlo standard error not suffer in the same way?
    A way to think about it

    Look at what the standard error formula contains. The dimension enters only through how variable ff is, not through the count of points.

  2. You use a standard normal proposal to estimate an expectation under a heavier-tailed target. What will the weights look like, and why is the result untrustworthy even if it looks stable?
    A way to think about it

    Far out in the tail the ratio of target to proposal is enormous, but such draws are rare. Think about what happens on the run where one finally appears.

  3. With a tiny proposal scale almost every Metropolis-Hastings move is accepted. Why is a very high acceptance rate a bad sign?
    A way to think about it

    Accepted steps that barely move leave consecutive samples almost identical. Relate that to the autocorrelations in the effective sample size formula.

  4. Rejection sampling of a standard normal target from a wide uniform box wastes most draws. What happens to the acceptance rate when the target is a product of 20 such normals in 20 dimensions?
    A way to think about it

    The acceptance rate in one dimension is a fraction below 1. Independent dimensions multiply, so raise it to the 20th power.

  5. Why can Metropolis-Hastings work with a density known only up to a constant, and why does that matter for Bayesian inference?
    A way to think about it

    The acceptance rule uses a ratio of target values. Recall which part of Bayes' theorem is the hard integral.