TExcelTAD
Home › Calculus Essentials › Numerical Integration

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 [a,b][a, b] into nn pieces of width h=(b−a)/nh = (b - a)/n, with points x0,x1,…,xnx_0, x_1, \ldots, x_n and values yi=f(xi)y_i = f(x_i).

Trapezoid:T=h⋅(y0/2+y1+y2+…+yn−1+yn/2)Simpson:S=(h/3)⋅(y0+4y1+2y2+4y3+…+4yn−1+yn)(n even)Monte Carlo:M=(b−a)⋅average of f at N random points\begin{aligned} \text{Trapezoid:}\quad T &= h \cdot (y_0/2 + y_1 + y_2 + \ldots + y_{n-1} + y_n/2) \\ \text{Simpson:}\quad S &= (h/3) \cdot (y_0 + 4y_1 + 2y_2 + 4y_3 + \ldots + 4y_{n-1} + y_n) && (n \text{ even}) \\ \text{Monte Carlo:}\quad M &= (b - a) \cdot \text{average of } f \text{ at } N \text{ random points} \end{aligned}

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 hh (or 4×N4 \times N) → error Exact for
Left/right Riemann hh ÷2\div 2 constants
Trapezoid h2h^2 ÷4\div 4 straight lines
Simpson h4h^4 ÷16\div 16 cubics
Monte Carlo 1/N1/\sqrt{N} ÷2\div 2 (needs 4× samples) nothing, but works in any dimension

Trapezoid and Simpson from scratch

Test case: ∫0πsin⁡x dx=2\int_0^\pi \sin x\,dx = 2.

python · try it yourself
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 nn 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 10−610^{-6}.

Monte Carlo

Monte Carlo replaces a grid with random points. Its error falls only like 1/N1/\sqrt{N}, which is slow in one dimension, but it does not care about dimension. A grid with 10 points per axis needs 10610^6 points in 6 dimensions; Monte Carlo's error at a given NN stays the same.

python · try it yourself
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 N=100N = 100 happened to land closer than N=10,000N = 10{,}000: Monte Carlo errors are random, and only the typical size, shrinking like 1/N1/\sqrt{N}, is predictable. (The 6-D exact value: the sum SS of six uniform numbers has mean 3 and variance 6/126/12, so E[S2]=0.5+9=9.5E[S^2] = 0.5 + 9 = 9.5.)

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.

python · try it yourself
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 (or trapezoid if 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 1/N1/\sqrt{N} 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 ∫02x3 dx\int_0^2 x^3\,dx with the trapezoid rule and n=2n = 2. The exact value is 4.

Answer

5

Solution
h=1,points 0,1,2,values 0,1,8T=1⋅(0/2+1+8/2)=5(too high: x3 curves upward, the chords lie above it)\begin{aligned} &h = 1, \quad \text{points } 0, 1, 2, \quad \text{values } 0, 1, 8 \\ &T = 1 \cdot (0/2 + 1 + 8/2) = 5 && \text{(too high: } x^3 \text{ curves upward, the chords lie above it)} \end{aligned}

Exercise 2: Simpson by hand

Estimate the same integral with Simpson's rule and n=2n = 2.

Answer

4, exact.

Solution
S=(1/3)⋅(0+4⋅1+8)=12/3=4Simpson’s rule is exact for polynomials up to degree 3.\begin{aligned} &S = (1/3) \cdot (0 + 4 \cdot 1 + 8) = 12/3 = 4 \\ &\text{Simpson's rule is exact for polynomials up to degree 3.} \end{aligned}

Exercise 3: Monte Carlo π\pi

The quarter disc x2+y2≤1x^2 + y^2 \le 1 in the unit square has area π/4\pi/4. Estimate π\pi with 1,000,000 random points from np.random.default_rng(1).

Answer

3.1432 with this seed. The typical error at this NN is about 0.0016, so the last digit is noise.

Solution
python · try it yourself
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 error(n)/error(2n)\text{error}(n) / \text{error}(2n) for ∫01ex dx\int_0^1 e^x\,dx with n=10n = 10. What does it tell you?

Answer

The ratio is about 4.04.0, confirming the trapezoid rule is second order (error∝h2\text{error} \propto h^2).

Solution
python · try it yourself
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?

  1. 2×
  2. 4×
  3. 16×
  4. It stays the same

Why do path-tracing renderers use Monte Carlo integration?

  1. It is exact
  2. Its error does not grow with the dimension of the integral
  3. It needs fewer samples than Simpson in 1-D
  4. It avoids random numbers

You have 50 evenly spaced measurements of a smooth signal. Which SciPy function fits?

  1. scipy.integrate.quad
  2. scipy.integrate.simpson
  3. scipy.optimize.minimize
  4. numpy.diff