Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

10. Monte Carlo methods

School of Engineering, Nazarbayev University

Track: advanced  ·  Prerequisites: Chapters 5 and 7

Reading: Bevington & Robinson, ch. 5 · Rouaud, ch. III.D · JCGM 101:2008 (GUM Supplement 1) · Press et al., Numerical Recipes, ch. 7

Monte Carlo simulation runs through this whole repository: to check propagation formulas, to verify the coverage of intervals, to propagate distributions through nonlinear models. This chapter looks at the method itself.

  1. Pseudo-random numbers and reproducibility.

  2. How to draw samples from a given distribution: inverse transform and rejection sampling.

  3. Correlated inputs.

  4. The accuracy of Monte Carlo results: how it scales with the number of samples, and how many samples are needed for a mean, a standard deviation or a 95 % interval.

  5. Variance reduction by stratified and Latin hypercube sampling.

10.1 Pseudo-random numbers

Computers generate pseudo-random numbers: a deterministic sequence that passes statistical tests of randomness. Two properties matter in practice.

  • Quality. Modern generators (NumPy’s default is PCG64) have periods far longer than any simulation and no detectable correlations in ordinary use. Older linear congruential generators, still found in some software, can have short periods and correlations between successive numbers.

  • Reproducibility. The sequence is fixed by a seed. Every notebook in this repository starts with np.random.default_rng(seed), so that its results can be reproduced exactly. A result that changes by more than its stated Monte Carlo uncertainty when the seed changes has been reported with too few samples.

10.2 Sampling from a distribution

Generators produce uniform numbers uu on [0,1)[0, 1); everything else is built from them.

Inverse transform. If F(x)F(x) is the cumulative distribution function of the target distribution, then x=F−1(u)x = F^{-1}(u) has that distribution, because P(x≤a)=P(u≤F(a))=F(a)P(x \le a) = P(u \le F(a)) = F(a). For the exponential distribution, F(x)=1−e−λxF(x) = 1 - e^{-\lambda x} and x=−ln⁡(1−u)/λx = -\ln(1-u)/\lambda; for the Cauchy distribution, x=x0+Γ2tan⁡[π(u−12)]x = x_0 + \tfrac{\Gamma}{2}\tan[\pi(u - \tfrac12)].

Rejection sampling. When F−1F^{-1} is not available, choose a simpler envelope distribution g(x)g(x) and a constant MM with p(x)≤Mg(x)p(x) \le M g(x) everywhere. Draw xx from gg and a uniform uu; accept xx if u Mg(x)<p(x)u\,M g(x) < p(x). The accepted values follow p(x)p(x), and the fraction accepted is 1/M1/M, so a tight envelope matters. Below, the angular distribution p(θ)∝1+cos⁡2θp(\theta) \propto 1 + \cos^2\theta (dipole radiation) is sampled with a uniform envelope.

Normal variables. The Box–Muller transform turns two uniform numbers into two independent standard normal ones: z1=−2ln⁡u1cos⁡2πu2z_1 = \sqrt{-2\ln u_1}\cos 2\pi u_2, z2=−2ln⁡u1sin⁡2πu2z_2 = \sqrt{-2\ln u_1}\sin 2\pi u_2. Libraries use faster methods, but the idea is the same.

exponential by inverse transform: mean 2.007 (expected 2.0), std 2.002 (expected 2.0)
Cauchy by inverse transform: median +0.0072, quartiles [-0.998  1.011] (expected -1, 1)
rejection sampling: acceptance 0.425;  <cos^2 theta> = 0.3999 (exact 0.4)
Box-Muller: mean +0.0013, std 1.0040, kurtosis excess +0.002

The acceptance rate of the dipole sampler is about 0.42 (the area under pp divided by the area of the envelope box), so more than half the effort is discarded; a better envelope would raise it.

10.3 Correlated inputs

To propagate correlated input quantities (Chapter 12) we need samples with a given covariance matrix C\mathsf C. Factor it as C=LLT\mathsf C = \mathsf L\mathsf L^{\mathsf T} (Cholesky decomposition) and set x=μ+Lz\boldsymbol x = \boldsymbol\mu + \mathsf L\boldsymbol z with z\boldsymbol z a vector of independent standard normal numbers. Then ⟨δx δxT⟩=L⟨zzT⟩LT=C\langle\delta\boldsymbol x\,\delta\boldsymbol x^{\mathsf T}\rangle = \mathsf L\langle\boldsymbol z\boldsymbol z^{\mathsf T}\rangle\mathsf L^{\mathsf T} = \mathsf C. This is what ep.monte_carlo(..., cov=C) does internally (through NumPy’s multivariate_normal).

target correlation:
 [[1.  0.8 0.2]
 [0.8 1.  0.5]
 [0.2 0.5 1. ]]
sample correlation:
 [[1.    0.8   0.201]
 [0.8   1.    0.5  ]
 [0.201 0.5   1.   ]]

10.4 How accurate is a Monte Carlo result?

A Monte Carlo estimate is itself a statistical estimate from MM samples, with an uncertainty that falls as 1/M1/\sqrt M whatever the number of input variables. This dimension-independence is what makes the method so useful. For MM independent samples of an output with standard deviation σ\sigma:

  • the mean has standard error σ/M\sigma/\sqrt M;

  • the standard deviation has relative standard error about 1/2M1/\sqrt{2M} for normal outputs (Section 4.3), larger for heavy-tailed ones;

  • a quantile qpq_p (for example the 2.5 % and 97.5 % points of a 95 % interval) has standard error

    u(qp)≈1f(qp)p(1−p)M,u(q_p) \approx \frac{1}{f(q_p)}\sqrt{\frac{p(1-p)}{M}} ,

    where ff is the probability density at the quantile. Since ff is small in the tails, tail quantiles converge slowly.

JCGM 101 recommends running the simulation until the quantities to be reported are stable to the number of digits quoted, and suggests at least M=106M = 10^6 trials for a 95 % interval when nothing better is known. The simulation below checks the three formulas.

    M     u(mean)    sigma/sqrt(M)    u(std)/std   1/sqrt(2M)    u(q97.5)   formula
    100   0.09711     0.10000         0.0742      0.0707      0.2462    0.2671
   1000   0.03207     0.03162         0.0212      0.0224      0.0841    0.0845
  10000   0.01060     0.01000         0.0074      0.0071      0.0276    0.0267
 100000   0.00306     0.00316         0.0023      0.0022      0.0083    0.0084

For M=104M = 10^4 the 97.5 % point is uncertain by about 0.03 standard deviations, enough to change the second significant figure of an expanded uncertainty. Reporting an interval to two significant figures needs M≈105M \approx 10^5 to 106.

10.5 Variance reduction: stratified and Latin hypercube sampling

Plain Monte Carlo can waste samples: by chance some regions of the input space are crowded and others empty. Stratified sampling divides the range of each input into MM equally probable strata and draws exactly one sample from each; for a single input this removes most of the sampling noise. With several inputs, full stratification would need MkM^k samples. Latin hypercube sampling (McKay, Beckman and Conover, 1979) stratifies each input separately and pairs the strata by random permutations, so each input is perfectly stratified with only MM samples.

The gain is largest for outputs that depend additively on the inputs and disappears for strongly interacting ones. Below, the standard deviation of the cylinder density of Chapter 3 (three inputs, nearly additive in the logarithm) is estimated with each method.

    M     spread of the estimated u(rho): plain MC    Latin hypercube    gain in M
    50                    0.0986              0.0540              3.3
   200                    0.0493              0.0259              3.6
  1000                    0.0212              0.0104              4.2
  5000                    0.0105              0.0051              4.2

For this nearly additive model, Latin hypercube sampling estimates the output standard deviation as precisely as plain Monte Carlo with about four times as many samples. (For the mean of an additive model the gain is far larger; for the standard deviation it is limited by the squared terms.) The gain matters when each model evaluation is expensive (a finite-element run, a molecular simulation). For cheap models, plain Monte Carlo with more samples is simpler and its statistical error is easier to state. Note that the samples of a Latin hypercube are not independent, so the simple error formulas of Section 10.4 do not apply to it; repeat the whole design with different seeds to estimate its error, as done here.

<Figure size 1012x792 with 4 Axes>

(a) Exponential samples from uniform numbers by the inverse transform. (b) Rejection sampling of a dipole angular distribution with a flat envelope. (c) Standard errors of Monte Carlo estimates of the mean, the standard deviation and the 97.5 % quantile of a normal output (symbols: repeated simulations; lines: formulas of Section 10.4). (d) Precision of the estimated output uncertainty with plain and Latin hypercube sampling.

Summary

  • Seed every simulation; a result should be stable to well within its Monte Carlo error when the seed changes.

  • Inverse transform and rejection sampling generate any distribution from uniform numbers; Cholesky factors generate correlated normals.

  • Monte Carlo errors fall as 1/M1/\sqrt M for every quantity, but with very different constants: tail quantiles need far more samples than means.

  • Latin hypercube sampling can save many model evaluations for nearly additive models; estimate its error by repeating the design.

References

  • JCGM 101:2008, Evaluation of measurement data, Supplement 1 to the “Guide to the expression of uncertainty in measurement”: Propagation of distributions using a Monte Carlo method.

  • W. H. Press, S. A. Teukolsky, W. T. Vetterling and B. P. Flannery, Numerical Recipes, 3rd ed. (Cambridge University Press, 2007), ch. 7.

  • M. D. McKay, R. J. Beckman and W. J. Conover, “A comparison of three methods for selecting values of input variables in the analysis of output from a computer code”, Technometrics 21, 239 (1979).

Exercises

  1. Sample the Rayleigh distribution p(r)=(r/σ2)e−r2/2σ2p(r) = (r/\sigma^2)e^{-r^2/2\sigma^2} by the inverse transform and check its mean σπ/2\sigma\sqrt{\pi/2}.

  2. Improve the envelope of the dipole sampler (for example g∝sin⁡θg \propto \sin\theta, sampled by inverse transform) and compare the acceptance rates.

  3. A covariance matrix estimated from data is sometimes not positive definite, and the Cholesky factorisation fails. Construct such a matrix from three pairwise correlations and explain why it cannot be a valid covariance matrix.

  4. How many samples are needed to estimate the 99.5 % quantile of a normal output to within 0.01 standard deviations?

  5. Repeat the comparison of Section 10.5 for the strongly nonlinear ratio a/ba/b of Section 12.4 (b=1.0±0.3b = 1.0 \pm 0.3). Does Latin hypercube sampling still help?