AI Wiki中文/EN

Monte Carlo integration

蒙特卡洛积分

Turn integration into sampling, and report uncertainty without confusing it with a guarantee.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Estimate an integral by averaging random evaluations

You need an average model loss over a distribution, but cannot evaluate every possible input. Draw representative inputs, evaluate the loss and average. Monte Carlo integration turns an integral into a statistical estimation problem.

Unlike a fixed-grid quadrature rule, its error is described through a sampling model. A different random sample gives a different answer. A reproducible seed preserves a particular experiment; it does not make that answer exact or establish its uncertainty by itself.

We estimate the integral of x² on [0,1], whose exact value 1/3 lets us inspect the method. Read integration, expectation and variance and random seeds first.

Convert the integral to an expectation

If U is uniform on [a,b], then an integrable function satisfies:

I=∫abf(x) dx=(b−a)E[f(U)],I^N=b−aN∑i=1Nf(Ui).I=\int_a^b f(x)\,dx=(b-a)\mathbb E[f(U)],\qquad \widehat I_N=\frac{b-a}{N}\sum_{i=1}^{N}f(U_i).

Under independent identically distributed sampling and finite expectation, this estimator is unbiased. With finite variance, independence removes the covariance terms when computing the variance of the average:

Var⁡(I^N)=(b−a)2Var⁡(f(U))N.\operatorname{Var}(\widehat I_N)=\frac{(b-a)^2\operatorname{Var}(f(U))}{N}.

Thus the root-mean-square error falls like 1/√N under these assumptions. Halving that error typically requires four times as many evaluations. The exponent does not explicitly contain dimension, but the integrand variance and sampling/evaluation cost can still grow badly with dimension. Owen’s Simple Monte Carlo chapter develops these guarantees and their limitations.

For f(u)=u² on [0,1], the mean is 1/3 and variance is 1/5−1/9=4/45. We therefore know the ideal sampling standard error exactly: √(4/(45N)). This is a property of repeated ideal IID experiments, not the error of a particular seeded run.

Estimate uncertainty from the sampled function values

Write Yᵢ=f(Uᵢ). On the unit interval, the usual sample-based standard error is:

s2=1N−1∑i(Yi−Y‾)2,SE^=sN,Y‾ ± 1.96SE^.s^2=\frac{1}{N-1}\sum_i(Y_i-\overline Y)^2,\qquad \widehat{\mathrm{SE}}=\frac{s}{\sqrt N},\qquad \overline Y\ \pm\ 1.96\widehat{\mathrm{SE}}.

The last expression is an approximate 95% interval justified by a suitable large-sample normal approximation. It is not a deterministic error bound and need not contain the true integral on every run. Tiny samples, heavy tails or missed rare events can make the approximation poor. The values whose variance is needed are the function outputs Y, not simply the sampled inputs U.

Owen also discusses numerically stable variance calculation. The program uses a centered two-pass calculation with fsum, avoiding subtraction of two large nearly equal second moments. It still uses floating-point arithmetic and is not a general-purpose arbitrary-precision estimator.

Run a reproducible experiment without hard-coding coverage

Use Python 3.12; no third-party packages are needed. The program accepts 2–100,000 samples and a nonnegative 32-bit integer seed. A private generator avoids altering global random state. Python’s random documentation describes its pseudorandom generator and reproducibility scope. The IID analysis is the ideal sampling model; executing a deterministic generator is not a proof of mathematical independence.

import math
import random


def summarize(values):
    if type(values) not in (list,tuple) or not 2 <= len(values) <= 100000:
        raise ValueError('2 to 100000 observations required')
    if any(type(v) not in (int,float) or not math.isfinite(v) or not 0 <= v <= 1 for v in values):
        raise ValueError('finite observations in [0,1] required')
    n=len(values);mean=math.fsum(values)/n
    variance=math.fsum((v-mean)**2 for v in values)/(n-1)
    se=math.sqrt(variance/n)
    return mean,se,(mean-1.96*se,mean+1.96*se)


def estimate(n,seed):
    if type(n) is not int or not 2 <= n <= 100000:
        raise ValueError('integer sample size in [2,100000] required')
    if type(seed) is not int or not 0 <= seed < 2**32:
        raise ValueError('integer seed in [0,2**32) required')
    rng=random.Random(seed)
    return summarize([rng.random()**2 for _ in range(n)])


if __name__ == '__main__':
    for n in [2000,8000]:
        mean,se,interval=estimate(n,2026)
        print('n='+str(n),'estimate='+format(mean,'.6f'),'estimated SE='+format(se,'.6f'),
              'approximate interval='+str(tuple(round(v,6) for v in interval)))
    print('exact integral:',format(1/3,'.6f'))
    print('ideal SE at n=2000:',format(math.sqrt(4/(45*2000)),'.6f'))

Recorded output:

n=2000 estimate=0.328821 estimated SE=0.006636 approximate interval=(0.315815, 0.341828)
n=8000 estimate=0.327163 estimated SE=0.003310 approximate interval=(0.320677, 0.33365)
exact integral: 0.333333
ideal SE at n=2000: 0.006667

The two runs reuse the seed, so the longer sequence includes the shorter one’s prefix. They are not independent replications. Their displayed standard errors may be compared as observations, but the exact factor-of-two reduction belongs to the ideal variance formula when N grows from 2000 to 8000. We do not assert that every larger sample is closer to the exact integral.

The implementation evaluates f N times and stores N outputs, using O(N) time and memory. A streaming mean/variance algorithm can reduce storage. The arithmetic result and uncertainty estimate should be reported separately from runtime measurements.

Sampling assumptions determine the error formula

Dependent samples add covariance terms. MCMC output therefore needs dependence-aware error analysis; inserting chain length into the IID formula can overstate precision. Importance sampling changes the evaluated quantity to a weighted one and needs adequate support and integrability conditions.

A rare event may not appear in a modest sample. An empirical variance near zero then need not imply a reliable estimate. Variance reduction, stratification and better proposals can be more effective than blindly increasing N, but each method changes the analysis.

Optional stopping also matters: repeatedly rerunning until an interval looks narrow or contains a desired answer is a different procedure from a fixed-N experiment. Use a stopping rule with appropriate guarantees when sequential decisions are required. None of these issues is resolved merely by recording a seed.

Distinguish sampling error from one observed discrepancy

  1. How many samples are typically needed to halve Monte Carlo standard error under the stated IID model?

Answer 1: Four times as many, because standard error scales as 1/√N.

  1. For the x² example, why estimate the variance of x² rather than the variance of x?

Answer 2: The estimator averages Y=x². Its variability is governed by Var(Y)=4/45, not Var(U)=1/12.

  1. Do two runs with the same seed and sample sizes 2000 and 8000 form independent replications?

Answer 3: No. With this generator usage, they share a prefix of the same pseudorandom sequence.

  1. Does an approximate 95% interval guarantee that this particular interval contains the true integral?

Answer 4: No. Its coverage concerns repeated sampling under assumptions and approximation. A particular interval can miss, and invalid assumptions can spoil coverage.

Improve the experiment before buying more samples

Owen’s chapter supplies the sampling theory, while Python’s reference identifies the concrete generator interface. The known integral separates mathematical variance from one execution’s observed error.

For a project, run several independently seeded fixed-size replications, compare their spread with the predicted standard error, and keep that finite experiment distinct from a proof of coverage. Then read importance sampling to change where computation is spent.

Make a prediction, then check

How should N change to halve ideal Monte Carlo standard error?

Choose one answer

Learning objectives

  • Derive an IID integration estimator and its variance.
  • Interpret estimated standard error and approximate coverage.

Prerequisites & connections

Explore related knowledge →

References

  1. Monte Carlo theory, methods and examples — Chapters 1–2
    Art B. Owen · 2013
  2. random — Generate Pseudo-random Numbers — Python 3.12
    Python Software Foundation and Python contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-agent authored technical review: primary-source locations, explicit assumptions, derivations, exact/literal and numerical checks, and bilingual review; not independent human or second-agent peer review.

  • Single-agent authored technical review: primary-source locations, explicit domains and assumptions, derivations, literal/exact probability or numerical reference cases, bilingual examples and exercises. Not independent human or second-agent review.
  • Four focused tests passed on CPython3.12.4; NumPy1.26.4 actually executed for the Fourier chapter. Exact rational probability/stencil checks are distinguished from floating-point calculations and observed Monte Carlo output. Both languages render three equations, six anchors and four answers; final repository checks recorded separately.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.