Monte Carlo and quasi-Monte Carlo integration
| Problem | Approximate integrals over boxes in many dimensions, where grids and cubature rules are too expensive |
| Devised by | Monte Carlo: Stanisław Ulam, John von Neumann and Nicholas Metropolis (1946–1949), after Buffon (1777). Low-discrepancy sequences: John Halton (1960), Ilya Sobol (1967). Random shifts: Roy Cranley and Thomas Patterson (1976) |
| Accuracy | Monte Carlo: standard error in every dimension. Quasi-Monte Carlo: often close to in practice for smooth integrands of low effective dimension (the bound is ) |
| Cost | One evaluation per point |
| Read first | Preliminaries: probability |
| API | monte_carlo, monte_carlo_integration, quasi_monte_carlo_integration, QuasiRandomSequence |
Overview
Every method in this chapter so far places its points deliberately, and pays for it in high dimensions: a cubature rule that resolves the integrand along each axis needs a number of points that grows exponentially with the dimension. Monte Carlo integration gives up on deliberate placement. It averages the integrand at random points, and the law of large numbers does the rest. Its error falls only like , slowly, but that rate does not depend on the dimension at all, which makes Monte Carlo the method of choice from about ten dimensions upwards, and the only practical one in hundreds.
Quasi-Monte Carlo keeps the simplicity of averaging but replaces random points by low-discrepancy sequences, deterministic points spread more evenly than random ones could be. For smooth integrands the error then falls nearly like . Randomising the sequence, as the library does, restores an honest error estimate.
Where it is used
When the number of variables is large, random sampling beats grids.
- Finance. Pricing derivatives and measuring risk involve expectations over many correlated variables.
- Physics and engineering. Radiative transfer, neutron transport, rendering of images by path tracing and reliability analysis of systems with uncertain inputs.
- Bayesian statistics. Posterior expectations are integrals over many parameters.
- Quasi-Monte Carlo. Low-discrepancy points improve the convergence rate for smooth integrands, as in computer graphics and finance.
History
The idea of estimating a number by random experiment is old. In 1777 Georges-Louis Leclerc, Comte de Buffon, showed that a needle dropped on ruled paper crosses a line with a probability involving , so that repeated throws estimate . Enrico Fermi used random sampling privately in the 1930s to study neutron diffusion.
The method acquired its name and its place in computing at Los Alamos. Recovering from an illness in 1946, the mathematician Stanisław Ulam wondered about the chance of winning a game of solitaire and realised it was easier to play many games and count than to calculate. With John von Neumann he saw that the same approach could solve the neutron transport problems of the weapons programme on the new ENIAC computer. Nicholas Metropolis suggested the name, after the casino where Ulam’s uncle gambled, and Metropolis and Ulam published “The Monte Carlo method” in 1949.
Quasi-random points grew from number theory and the study of uniform distribution. John Halton (1960) and Ilya Sobol (1967) constructed sequences whose points fill the unit cube far more evenly than random ones, and the Koksma-Hlawka inequality (Jurjen Koksma 1942, Edmund Hlawka 1961) explained why they integrate better. Roy Cranley and Thomas Patterson (1976) showed how to randomise such points with a random shift, which brought back error estimates, and Art Owen (1995) introduced the more powerful randomisation by scrambling.
The idea
Monte Carlo as an average
Let be the volume of the box and a random point uniformly distributed in . Then , and with independent samples the natural estimate is
It is unbiased, , and since the samples are independent its variance is , where . By the central limit theorem the error is approximately normally distributed with standard deviation
Two facts make this remarkable. The dimension of the box appears nowhere: only the variance of the integrand matters. And the error can be estimated from the same samples, by replacing with the sample standard deviation. The price is the rate: one more correct digit costs a hundred times as many samples.
Table 2.18. Monte Carlo error and its estimate against dimension.
| dimension | Monte Carlo error () | standard error | randomised Halton error () | tensor rule with 2 points per axis | |
|---|---|---|---|---|---|
| 1 | 0.5 | 1.7e-3 | 1.6e-3 | 1.5e-5 | 2 evaluations |
| 5 | 0.5 | 1.3e-3 | 1.6e-3 | 4.0e-5 | 32 evaluations |
| 20 | 0.5 | 1.7e-3 | 1.6e-3 | 1.4e-5 | 1048576 evaluations |
| 50 | 0.5 | 1.1e-3 | 1.6e-3 | 3.1e-4 | 1.1e15 evaluations |
For an integrand with the same variance in every dimension, the Monte Carlo error with points is the same in one dimension as in fifty, while even the crudest product rule would need evaluations.
An honest error estimate
The sample variance must be computed carefully. The textbook formula subtracts two nearly equal numbers when the mean is large compared with the spread. Welford’s algorithm updates the mean and the sum of squared deviations one sample at a time:
so that , without cancellation. The library’s tests check that the estimate is honest: over many seeds, about 68% of estimates lie within one standard error of the true value, as the normal distribution predicts.
A stopping rule must use this standard error. It is tempting to stop “when the estimate stops
changing”, but successive running averages share almost all their samples, so they agree with each
other long before they agree with the integral. monte_carlo_integration
samples in batches until the standard error falls below the requested target.
Low-discrepancy sequences
Random points leave gaps and clusters, and the rate is the price of that unevenness. The star discrepancy of a point set measures it: the largest difference, over all boxes anchored at the origin, between the fraction of points inside the box and its volume. Random points have . Low-discrepancy sequences achieve .
Figure 2.17. Random points, Sobol points and Halton points.
The Halton sequence uses the radical inverse: write in base , reflect its digits about the decimal point (), and use a different prime base for each coordinate. The Sobol sequence works in base 2 throughout, with carefully chosen “direction numbers” for each coordinate, and its first points are stratified: in two dimensions every box of the form with area contains exactly one of them, and in higher dimensions the same holds for somewhat larger boxes. Both are generated in the random crate.
Koksma-Hlawka inequality. For points in and of bounded variation in the sense of Hardy and Krause,
The error therefore separates into a property of the integrand and a property of the points, and low-discrepancy points give an error bound of order . That bound is asymptotic and pessimistic: for and , is larger than , so the bound says nothing yet. The behaviour seen below is an observation about smooth integrands whose variation is concentrated in a few coordinates, not a consequence of the inequality.
Randomised quasi-Monte Carlo
Deterministic points have one drawback: the bound above is almost impossible to evaluate, so there is no practical error estimate. The Cranley-Patterson shift adds the same uniformly random vector to every point, modulo 1. Each shifted point is uniformly distributed, so the estimate is unbiased, while the even spacing of the set is preserved. Repeating with independent shifts gives independent estimates, and their spread gives a standard error, exactly as in Monte Carlo.
Figure 2.18. Monte Carlo against randomised quasi-Monte Carlo.
For this smooth five-dimensional integrand, Monte Carlo follows the line and the randomised Sobol and Halton points follow : at they are about fifty times more accurate. The advantage shrinks as the dimension grows and as the integrand becomes rougher. The last column of the table above shows the randomised Halton error growing with the dimension, from in one dimension to in fifty.
Algorithm
Monte Carlo (monte_carlo): for , draw uniformly in the box and update
Welford’s mean and with . Return and .
Monte Carlo to a target (monte_carlo_integration): sample in batches; after each batch, stop if
the standard error is below the target, or return the current estimate once the sample limit is
reached.
Randomised QMC (quasi_monte_carlo_integration): generate the first points of the Sobol or
Halton sequence; for , draw a random shift, average over the shifted points
mapped to the box, and record the estimate. Return the mean of the estimates and their standard
error.
Implementation
Welford’s update and the standard error:
fn push(&mut self, y: f64) {
self.n += 1;
let delta = y - self.mean;
self.mean += delta / self.n as f64;
self.m2 += delta * (y - self.mean);
}
/// The standard error of the mean, `σ̂ / √n`.
fn standard_error(&self) -> f64 {
if self.n < 2 { f64::INFINITY } else { (self.m2 / (self.n - 1) as f64 / self.n as f64).sqrt() }
}
- The random generator is seeded explicitly, so results are reproducible.
- For Sobol points, use a power of two for : the stratification property holds for the first points, and partial blocks integrate less evenly.
- With a single replicate the QMC standard error is not available (it is returned as NaN); 8 to 32 replicates are typical.
In practice
//! Monte Carlo and randomised quasi-Monte Carlo integration, with error estimates.
//!
//! Run with `cargo run -p lib_jsl_integration --example quadrature_monte_carlo`.
use lib_jsl_integration::monte_carlo_integration::{monte_carlo, monte_carlo_integration};
use lib_jsl_integration::quasi_monte_carlo::{QuasiRandomSequence, quasi_monte_carlo_integration};
fn main() {
// The volume of the unit ball in 6 dimensions, π³/6, as ∫ of an indicator over [−1, 1]⁶.
let exact = std::f64::consts::PI.powi(3) / 6.0;
let ball = |x: &[f64]| if x.iter().map(|v| v * v).sum::<f64>() <= 1.0 { 1.0 } else { 0.0 };
let cube = vec![(-1.0, 1.0); 6];
for n in [1_000, 10_000, 100_000, 1_000_000] {
let r = monte_carlo(ball, &cube, n, 42).unwrap();
println!("N = {n:>9}: {:.5} ± {:.5} (true error {:.5})", r.value, r.standard_error, (r.value - exact).abs());
}
// Sampling until a target standard error is reached.
let v = monte_carlo_integration(ball, &cube, (0.01, 10_000), None).unwrap();
println!("to a standard error of 0.01: {v:.4} (exact {exact:.4})");
// A smooth integrand in 8 dimensions: randomised Sobol points beat random ones.
let smooth = |x: &[f64]| x.iter().map(|v| (1.0 + v).ln() / (2.0 * 2f64.ln() - 1.0)).product::<f64>();
let unit = vec![(0.0, 1.0); 8];
let mc = monte_carlo(smooth, &unit, 1 << 16, 1).unwrap();
let qmc = quasi_monte_carlo_integration(smooth, &unit, 1 << 13, 8, QuasiRandomSequence::Sobol, 1).unwrap();
println!("8-dimensional product, 65536 evaluations each:");
println!(" Monte Carlo error {:.1e}, standard error {:.1e}", (mc.value - 1.0).abs(), mc.standard_error);
println!(" randomised Sobol error {:.1e}, standard error {:.1e}", (qmc.value - 1.0).abs(), qmc.standard_error);
}
Strengths
- Works in any dimension, with an error that depends on the variance and not on the dimension.
- Needs nothing of the integrand beyond the ability to evaluate it; discontinuities, such as the indicator of a ball, are no obstacle.
- Gives an honest, cheap error estimate.
- Quasi-Monte Carlo is often ten to a thousand times more accurate for smooth integrands at no extra cost.
Weaknesses
- Slow: the rate makes high accuracy prohibitively expensive.
- Integrands with large or infinite variance (for example strong singularities) converge slowly or not at all, and the error estimate then becomes unreliable too.
- The QMC advantage fades in very high dimensions unless the integrand depends mostly on a few variables or on low-order interactions.
The variance can often be reduced: by importance sampling (drawing points from a density resembling ), control variates (subtracting a function with a known integral) or stratification. These methods appear with the random number generation tools in a later chapter.
Exercises
- Show that and .
- Estimate from the area of the unit disc with Monte Carlo, and determine how many points are needed for six correct digits.
- Compute the first eight points of the base-2 and base-3 radical inverses by hand, and check them
against
HaltonSequence. - Integrate over for with Monte Carlo and randomised Sobol at . How does the advantage of QMC change, and why?
- For , the variance of is infinite. What happens to the Monte Carlo estimate and its standard error as grows?
Hints and answers
- . Independence makes variances add: .
- The hit fraction has standard deviation , so has standard error . For six correct digits (error below ) you need .
- Base 2: . Base 3: . The library’s Halton sequence starts after the origin, so these are its first terms.
- The exact integral is 1. Each factor has variance , so , which grows from at to about at . The function is a product of one-dimensional pieces with weak interactions, so QMC keeps a large advantage, which narrows as grows.
- The mean is finite, so the estimate still converges (law of large numbers), but the variance is infinite, so the central limit theorem does not apply: convergence is slower than and erratic, and the sample standard error is unreliable and tends to be too small.
Further reading
- N. Metropolis and S. Ulam, “The Monte Carlo method”, Journal of the American Statistical Association 44 (1949) 335–341.
- R. Eckhardt, “Stan Ulam, John von Neumann, and the Monte Carlo method”, Los Alamos Science 15 (1987) 131–137. The history, from those who were there.
- J. H. Halton, “On the efficiency of certain quasi-random sequences of points in evaluating multi-dimensional integrals”, Numerische Mathematik 2 (1960) 84–90.
- I. M. Sobol, “On the distribution of points in a cube and the approximate evaluation of integrals”, USSR Computational Mathematics and Mathematical Physics 7 (1967) 86–112.
- R. Cranley and T. N. L. Patterson, “Randomization of number theoretic methods for multiple integration”, SIAM Journal on Numerical Analysis 13 (1976) 904–914.
- B. P. Welford, “Note on a method for calculating corrected sums of squares and products”, Technometrics 4 (1962) 419–420.
- A. B. Owen, Monte Carlo Theory, Methods and Examples, 2013, online at https://artowen.su.domains/mc/. A modern textbook covering both methods.