Numerical Integration
Most integrals that matter in practice have no formula, or the function is only known as measured samples. Numerical integration computes the number directly. This lesson builds the trapezoid rule, Simpson's rule and Monte Carlo integration from scratch, compares their accuracy, and checks them against SciPy.
Three rules
Split into pieces of width , with points and values .
The trapezoid rule joins neighbouring points with straight lines; Simpson's rule fits a parabola through each group of three points; Monte Carlo just samples.
| Method | Error shrinks like | Halve (or ) → error | Exact for |
|---|---|---|---|
| Left/right Riemann | constants | ||
| Trapezoid | straight lines | ||
| Simpson | cubics | ||
| Monte Carlo | (needs 4× samples) | nothing, but works in any dimension |
Trapezoid and Simpson from scratch
Test case: .
import math
def trapezoid(f, a, b, n):
h = (b - a) / n
s = (f(a) + f(b)) / 2 + sum(f(a + i * h) for i in range(1, n))
return h * s
def simpson(f, a, b, n): # n must be even
h = (b - a) / n
s = f(a) + f(b)
s += 4 * sum(f(a + i * h) for i in range(1, n, 2))
s += 2 * sum(f(a + i * h) for i in range(2, n, 2))
return h / 3 * s
print(" n trapezoid error simpson error")
for n in [4, 8, 16, 32]:
et = trapezoid(math.sin, 0, math.pi, n) - 2
es = simpson(math.sin, 0, math.pi, n) - 2
print(f"{n:4d} {et:15.2e} {es:13.2e}") n trapezoid error simpson error
4 -1.04e-01 4.56e-03
8 -2.58e-02 2.69e-04
16 -6.43e-03 1.66e-05
32 -1.61e-03 1.03e-06
Each time doubles, the trapezoid error drops about 4× and Simpson's about 16×, as the table predicted. With 32 intervals Simpson's error is already about .
Monte Carlo
Monte Carlo replaces a grid with random points. Its error falls only like , which is slow in one dimension, but it does not care about dimension. A grid with 10 points per axis needs points in 6 dimensions; Monte Carlo's error at a given stays the same.
import numpy as np
rng = np.random.default_rng(7)
# 1-D: ∫_0^π sin x dx = 2
for N in [100, 10_000, 1_000_000]:
x = rng.uniform(0, np.pi, N)
est = np.pi * np.sin(x).mean()
print(f"N={N:>9,} estimate={est:.5f} error={est - 2:+.5f}")
# 6-D: ∫ over the unit cube of (x1+…+x6)^2, exact value 9.5
pts = rng.uniform(0, 1, size=(200_000, 6))
print(f"6-D estimate = {(pts.sum(axis=1) ** 2).mean():.4f} (exact 9.5)")N= 100 estimate=1.99775 error=-0.00225
N= 10,000 estimate=1.98936 error=-0.01064
N=1,000,000 estimate=2.00086 error=+0.00086
6-D estimate = 9.4949 (exact 9.5)
Notice that happened to land closer than : Monte Carlo errors are random, and only the typical size, shrinking like , is predictable. (The 6-D exact value: the sum of six uniform numbers has mean 3 and variance , so .)
SciPy
In real code use scipy.integrate. quad is adaptive: it puts more points where the function is hard and reports an error estimate. trapezoid and simpson work on sampled data. See SciPy Integration for more.
import numpy as np
from scipy.integrate import quad, trapezoid, simpson
f = lambda x: np.exp(-x**2) # no elementary antiderivative
val, err = quad(f, 0, 1)
print(f"quad : {val:.10f} (error estimate {err:.1e})")
x = np.linspace(0, 1, 11) # 11 samples, like sensor data
print(f"trapezoid : {trapezoid(f(x), x):.10f}")
print(f"simpson : {simpson(f(x), x=x):.10f}")quad : 0.7468241328 (error estimate 8.3e-15)
trapezoid : 0.7462107961
simpson : 0.7468249483
Tip: Smooth function you can evaluate anywhere →
quad. Fixed samples →simpson(ortrapezoidif the data is noisy or uneven). Many dimensions → Monte Carlo.
In software
- Rendering: the brightness of a pixel in a path tracer is an integral of incoming light over all directions (the rendering equation). Renderers estimate it by Monte Carlo, shooting random rays; the "noise" in a quick render is exactly the error, which is why doubling quality costs four times the rays.
- ML: expected losses, Bayesian posteriors and variational methods are high-dimensional integrals estimated by sampling.
- Finance: option prices are expectations computed by Monte Carlo over simulated price paths.
- Games and physics: each step of a physics engine integrates acceleration and velocity numerically; see Integrators.
Exercises
Exercise 1: Trapezoid by hand
Estimate with the trapezoid rule and . The exact value is 4.
Answer
5
Solution
Exercise 2: Simpson by hand
Estimate the same integral with Simpson's rule and .
Answer
4, exact.
Solution
Exercise 3: Monte Carlo
The quarter disc in the unit square has area . Estimate with 1,000,000 random points from np.random.default_rng(1).
Answer
3.1432 with this seed. The typical error at this is about 0.0016, so the last digit is noise.
Solution
import numpy as np
rng = np.random.default_rng(1)
p = rng.uniform(0, 1, size=(1_000_000, 2))
inside = (p ** 2).sum(axis=1) <= 1
print(f"pi ≈ {4 * inside.mean():.4f}")pi ≈ 3.1432
Exercise 4: Measure the order
Using your trapezoid function, compute the error ratio for with . What does it tell you?
Answer
The ratio is about , confirming the trapezoid rule is second order ().
Solution
import math
def trapezoid(f, a, b, n):
h = (b - a) / n
return h * ((f(a) + f(b)) / 2 + sum(f(a + i * h) for i in range(1, n)))
exact = math.e - 1
e10 = trapezoid(math.exp, 0, 1, 10) - exact
e20 = trapezoid(math.exp, 0, 1, 20) - exact
print(f"{e10:.3e} {e20:.3e} ratio {e10 / e20:.3f}")1.432e-03 3.580e-04 ratio 4.000
Test yourself
Doubling the number of intervals in Simpson's rule makes the error about how much smaller for a smooth function?
- 2×
- 4×
- 16×
- It stays the same
Why do path-tracing renderers use Monte Carlo integration?
- It is exact
- Its error does not grow with the dimension of the integral
- It needs fewer samples than Simpson in 1-D
- It avoids random numbers
You have 50 evenly spaced measurements of a smooth signal. Which SciPy function fits?
- scipy.integrate.quad
- scipy.integrate.simpson
- scipy.optimize.minimize
- numpy.diff