Numerical integration
import { trapezoidalRule } from "@ac-kit/math-analysis";Where you meet it. Total energy consumed from a power reading taken every second. Distance travelled from a speed log. The area under a precision-recall curve. Expected value of anything described by a density you can evaluate but not integrate on paper — which is most of them.
The rule
Section titled “The rule”trapezoidalRule() splits [lower, upper] into
intervals equal panels, evaluates f at each boundary, and sums the
trapezoids.
Each panel is wrong by however much the real curve bulges away from the straight
line across it. That error shrinks as O(h²) in the panel width h, which
means something concrete and checkable: double the number of panels and the
error should quarter.
EvidenceThe error quarters each time the panel count doubles, which is the O(h²) rate.
The trapezoidal rule is second orderReplacing the integrand with the straight line across each panel leaves an error of O(h²), so every doubling of the panel count should quarter it. On a log-log axis that is a straight line of slope −2, drawn here against a reference line of exactly that slope. Follow it far enough right and the measured curve leaves the reference: the discretisation error has fallen below the accumulated rounding error, and adding panels stops helping.
const { f, lower, upper, exact } = INTEGRALS[integral];
const panels: number[] = [];const errors: number[] = [];const reference: number[] = [];
for (let power = 1; power <= doublings; power++) { const intervals = 2 ** power; const approximation = trapezoidalRule(f, lower, upper, intervals); panels.push(intervals); errors.push(Math.max(Math.abs(approximation - exact), Number.MIN_VALUE)); // Anchored at the first measured point, so only the slope is being compared. reference.push((errors[0] as number) * (2 / intervals) ** 2);}
const frame = curveFrame( panels, [ { name: "measured error", values: errors }, { name: "O(h²) reference", values: reference }, ], { x: "panels", y: "error", series: "quantity" },);Where it stops improving
Section titled “Where it stops improving”Push the panel count far enough and the measured error leaves the theoretical line and flattens out. Nothing is broken — the discretisation error has fallen below the rounding error accumulated across all those additions, and beyond that point adding panels buys nothing but time.
That floor is why “just use more panels” is not a strategy. Getting past it needs a better rule, not a finer one.
Further reading
- Trapezoidal rule (Wikipedia)background
- Numerical integration (Wikipedia)background
- DLMF §3.5 — Quadratureauthoritative