The trapezoidal rule is the first quadrature rule anyone learns. Cut \([a, b]\) into \(n\) pieces of width \(h\), draw a straight line over each piece and add up the areas. For \(f(x) = x^2\) on \([0, 1]\) the exact answer is

$$ \int_0^1 x^2 \, dx = \frac{1}{3}, $$

and with ten pieces the rule gets \(0.335\). Written out, the composite rule is \(\int_a^b f(x)\,dx \approx \frac{h}{2}\left(f(x_0) + 2f(x_1) + 2f(x_2) + \dots + 2f(x_{n-1}) + f(x_n)\right)\), and its error shrinks like \(h^2\): twice as many points, a quarter of the error. That’s the textbook story, and the reason the rule usually gets replaced by Simpson’s or Gauss’s.

In Python it fits in three lines:

def trapezoid(f, a, b, n):
    h = (b - a) / n
    return h * (f(a) / 2 + sum(f(a + i * h) for i in range(1, n)) + f(b) / 2)

Now try it on a periodic function over a full period, say \(e^{\cos x}\) on \([0, 2\pi]\). The error doesn’t shrink like \(h^2\) any more but faster than any power of \(h\): with twenty points it’s already at machine precision. The error terms that usually spoil the rule cancel at the two ends, because the ends are the same point.

Rates like \(h^2\) are the bread and butter of my thesis, only for finite elements instead of sums. A typical result looks like this, and it says no more than the one above: the finer the mesh, the smaller the error, at a known rate.

$$ \left\lVert u - u_h \right\rVert_{L^2(\Omega)} \le C h^{p+1} \left\lvert u \right\rvert_{H^{p+1}(\Omega)} \quad\text{for all}\quad u \in H^{p+1}(\Omega) \cap H^1_0(\Omega),\ h \to 0 $$

The purpose of computing is insight, not numbers.

Richard Hamming