From first principles
Integrate the line joining two function values
To estimate accumulated area from sampled values, specify how the function is approximated between samples. On one panel of width \(h\), connect \(f(a)\) and \(f(a+h)\) by a straight line. Its integral is its mean height times its width,
Summing panels on a uniform mesh counts every interior value twice and each boundary value once. If \(|f''|\le M\), the linear interpolation remainder at distance \(s\) from the left edge is bounded by \(Ms(h-s)/2\). Integrating that bound and adding all panels gives
Halving the step therefore quarters the upper bound for a fixed interval. The actual error can be smaller if curvature changes sign and panel errors cancel. Endpoint singularities or jumps can violate the smoothness assumption and require separate treatment.
Derivation and applications
Explain why periodic trapezoidal quadrature can be unusually accurate
For a periodic smooth signal, the nominal second-order trapezoidal bound can substantially underestimate the observed accuracy. Consider one full period \([0,2\pi]\) and \(N\) equally spaced samples \(x_j=2\pi j/N\). Since the first and final endpoints agree, their half weights combine. For one complex Fourier mode indexed by integer \(k\), the sample mean is a geometric series,
For the second case the ratio is a nontrivial \(N\)th root of unity; the numerator of the finite sum vanishes. The exact period integral of a nonconstant Fourier mode also vanishes. Expand a signal with absolutely summable Fourier coefficients so summation and sampling can be interchanged. The grid integrates exactly those nonconstant modes which do not alias into the constant mode,
The full quadrature error is therefore determined by the sampled multiples of \(N\). For a signal with \(|c_k|\le Cq^{|k|}\), \(0<q<1\), summing the two geometric tails gives
The conclusion depends on covering a complete period with the matched endpoints. A smooth nonperiodic signal generally acquires a discontinuity or derivative mismatch under periodic extension, changing the coefficient decay.
Worked example
Detect the only troublesome harmonic
Integrate \(f(x)=2+\cos(3x)+0.1\cos(8x)\) with eight equally spaced points around a full period. The true integral is \(4\pi\). The third harmonic cancels across the grid, but \(\cos(8x_j)=1\) at every sample. Thus \(T_8=4.2\pi\), an excess of \(0.2\pi\). With nine equally spaced points neither harmonic aliases into zero frequency, so the integral becomes exact.
Second application
Select a point count from measured spectral decay
For a different periodic signal assume the coefficient envelope is verified with \(C=1\), \(q=1/2\). To keep absolute integral error below \(0.010\), require \(4\pi/(2^N-1)<0.010\). Ten points give a bound \(0.0123\), while eleven give \(0.00614\). The latter is the smallest count certified by this envelope; the actual signal may converge faster through cancellations.
OneSimulation laboratory
Measure what interpolation does to a heat integral
Start from this chapter. Integrate each linear interpolant and add the cell contributions. Compare the resulting trapezoidal bias for a quadratic temperature law and for a linear law on identical nodes.
Compare recorded OneSimulation runs on this page. To test your own inputs, download the Python model and run the model in an activated OneSimulation environment.
OneSimulation maps source samples to the original nodes and their midpoints. Integrating those segments gives the area under the interpolant. Keep the quadratic temperature law and double the number of source intervals. Then restore four intervals and replace the quadratic law with \(300+20x/L\). Download the Python experiment · OneSimulation point interpolation.
python approximation-and-quadrature.py
python approximation-and-quadrature.py --cells 8
python approximation-and-quadrature.py --law linear
| Profile, intervals | Max. midpoint error (K) | Integral (K·m) | Integral error (K·m) |
|---|---|---|---|
| Quadratic, 4 | 0.3125 | 306.875 | +0.208333 |
| Quadratic, 8 | 0.078125 | 306.71875 | +0.0520833 |
| Linear, 4 | 0 | 310 | 0 |

Halving the spacing divides both quadratic-profile errors by four. The linear-profile result tests exactness on the function space represented by the interpolant.
Change parameters · Change the laboratory inputs
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Problem sheet 2 · Recover an integral using two biased readings
Measure an integral with finite samples
The energy delivered by a time-varying power input is the area under its history. If readings are available only at a fixed interval, integration must proceed from those samples or from additional physical assumptions. On one panel \([a,a+h]\), the midpoint rule uses \(hf(a+h/2)\), while integration of the chord between the endpoints gives \(h[f(a)+f(a+h)]/2\). Both are exact for affine \(f\). They may nonetheless give opposite errors on the same curved signal, which makes their comparison informative.
Expand about the midpoint \(m\), using \(s=x-m\). Odd powers of \(s\) integrate to zero on \([-h/2,h/2]\). The leading correction to \(hf(m)\) is \(f''(m)h^3/24\). Averaging the endpoint expansions instead gives \(hf(m)+f''(m)h^3/8+O(h^5)\). Subtracting the integral, the leading trapezoidal overestimate is \(+f''(m)h^3/12\), while the midpoint estimate has leading error \(-f''(m)h^3/24\). This expansion requires a smooth integrand. At a known abrupt switch in power, align a panel edge with the switch before applying it.
OneSimulation · Move one unresolved corner between quadrature points
A one-second power trace has the form \(P(t)=a|t-c|\), with slope magnitude \(a=1\) W/s. Every panel away from the corner contains a straight line and contributes its exact energy. On the remaining panel put the corner a fraction \(\theta\) along a width \(h\). Splitting its area into two triangles and subtracting their sum from the midpoint approximation gives
The sign follows directly from convexity. For eight panels the largest deficit is 3.90625 mJ. OneSimulation supplies the physical Gauss points and weights for each line element. The second sweep uses two Gauss points on exactly the same mesh. When the corner is central this rule overshoots by 0.6043 mJ. Its cubic exactness applies on a single smooth polynomial panel; the corner joins two different polynomials. Splitting the panel at the known corner makes either rule exact.
"""Slide a V-shaped power trace across an unchanged quadrature mesh."""
import matplotlib.pyplot as plt
import numpy as np
from onesim.cad.d1 import Line
from onesim.meshing import StructuredLineMesher
from onesim.numerics.fem.backends.spaces.line_lagrange import LineLagrangeSpace
cells = 8
line = Line(start=(0, 0, 0), end=(1, 0, 0)) # time interval, seconds
mesh = StructuredLineMesher(cells=cells).generate(line)
space = LineLagrangeSpace(mesh, order=1)
width = 1 / cells
fraction = np.linspace(0, 1, 121)
corner = (3 + fraction) * width # position in fourth panel (s)
exact = (corner**2 + (1 - corner)**2) / 2 # J at 1 W/s
fig, ax = plt.subplots(figsize=(6.8, 3.8), constrained_layout=True)
for count, colour in [(1, "#176879"), (2, "#a4492b")]:
energy = np.zeros_like(corner)
for cell in range(cells):
points, weights = space.quadrature(cell, order=count)
power = np.abs(points[:, 0, None] - corner) # W at 1 W/s
energy += weights @ power
error = energy - exact
if count == 1:
predicted = -width**2 * np.minimum(fraction, 1 - fraction)**2
assert np.allclose(error, predicted)
assert np.allclose(error[[0, -1]], 0)
ax.plot(fraction, 1000 * error, color=colour, label=f"{count} Gauss point(s) per panel")
print(f"{count} point(s): centre error {1000*error[len(error)//2]:+.4f} mJ")
ax.axhline(0, color="#555", lw=0.8)
ax.set(xlabel="Corner position within one panel (fraction)", ylabel="Computed minus exact energy (mJ)")
ax.legend()
fig.savefig("approximation-and-quadrature.png", dpi=160)

Increase the order by cancelling a term
Cover a fixed interval with equal panels. There are \(O(1/h)\) local errors of order \(h^3\), giving global second-order accuracy for both rules. Now combine two parts midpoint and one part trapezoid. Their leading second-derivative terms cancel. On a panel of width \(H\), the result is \(H[f(a)+4f(a+H/2)+f(a+H)]/6\), Simpson’s rule. It integrates all cubics exactly: the quadratic error cancels and odd terms about the midpoint cancel by symmetry. For sufficiently smooth data the panel error is \(O(H^5)\) and the composite error is \(O(H^4)\).
Simpson’s formula needs midpoint readings. With an even number of equal subintervals, join consecutive pairs and obtain the familiar alternating weights \(1,4,2,4,\dots,4,1\). Applying those integer weights to unequally spaced observations loses the derivation. In that setting use correctly derived nonuniform weights or the trapezoidal rule panel by panel.
Check the signs with a quartic pulse
Let \(P(t)=t^4\) W with \(t\) measured numerically in seconds over \([0,1]\). The exact energy is \(1/5\) J. With one whole panel, the midpoint estimate is \(1/16=0.0625\) J and the trapezoidal estimate is 0.5 J. Convexity explains why the true integral falls between them. Simpson gives
Its positive error of \(1/120\) J is much smaller, though the quartic term prevents exactness.
Now split into two Simpson panels. The fourth derivative is constant, so halving panel width reduces the global error by exactly 16. The new estimate is \(0.2+(1/120)/16=0.20052083\) J. In a real measurement, noise can dominate such a small discretisation improvement. A common positive bias of 0.01 W integrates to an extra 0.01 J regardless of panel count. Distinguish uncertainty on the measurements from the discretisation of a known smooth curve. The rod experiment provides a direct check of the trapezoidal error sign and its reduction on mesh refinement. Measure the area under a sampled profile.
Build a Romberg table from nested panels
On a smooth interval the composite trapezoid often admits the even-power expansion \(T(h)=I+c_2h^2+c_4h^4+\cdots\). Combining two grid estimates can remove the first term. Romberg integration repeats that cancellation on successive columns. Set \(R_{j,0}=T(h_0/2^j)\). If column \(m-1\) has leading error proportional to \(h^{2m}\), halving \(h\) divides that term by \(4^m\). Solving the two leading error equations for the common limit gives
The second extrapolation therefore uses 15 in its denominator, where the first extrapolation used three. Existing readings can be reused: halving the step retains the old trapezoid with half its old weight and adds the new midpoint samples with the fine spacing. The \(j\)th row thus needs only the newly introduced points. Each extra cancellation requires enough smoothness for another term in the expansion. A jump, an endpoint singularity or noisy samples may destroy the expected pattern.
To integrate \(1/(1+x)\) on \([0,1]\), the trapezoids with one, two and four panels give \(3/4,\ 17/24,\ 1171/1680\). The two first extrapolations are \(R_{1,1}=25/36\approx0.6944444\) and \(R_{2,1}=1747/2520\approx0.6932540\). Using the second denominator yields
The exact answer is \(\log2\approx0.6931472\), so the error falls from about 0.003877 in the four-panel trapezoid to 0.0000274 after the second cancellation. Altogether only five distinct function locations were used. Compare columns of the same order before interpreting changes along the diagonal as a convergence measurement.
Practise on sheet 2 · Does three-level extrapolation integrate every smooth input exactly?. Further reading · University of California, Berkeley · Math 128A Numerical Analysis, lecture notes · Chapter 4, Numerical Differentiation and Integration, §4.5 Romberg Integration.
Handle a jump with one-sided values
Consider a heater that supplies 4 W until \(t=0.3\) s and 1 W from then to one second. The energy is
A two-panel trapezoidal rule reading at 0, 0.5 and 1 s sees the values 4, 1 and 1. It predicts
The piecewise linear representation invents a sloping transition lasting half a second.
If the switch time is known, split there and use the left and right limiting powers separately. Each constant segment then integrates exactly, including the correct jump without treating an isolated endpoint as carrying energy. If the switch time itself has uncertainty 0.01 s, the resulting energy uncertainty is 0.03 J because the power level changes by 3 W. Refining a numerical integration grid cannot resolve that timing uncertainty by itself.
Turn known endpoint slopes into a quadrature correction
For a uniform composite trapezoid rule on \([a,b]\), examine a single panel by expanding the integrand symmetrically around its midpoint \(m\). The panel trapezoid value is \(h f(m)+h^3 f''(m)/8+O(h^5)\); integrating that same expansion gives \(h f(m)+h^3 f''(m)/24+O(h^5)\). The excess of the panel trapezoid is therefore \(h^3 f''(m)/12+O(h^5)\). Summing over the panels brings in the midpoint approximation to the integral of \(f''\). Its leading continuous value is \(f'(b)-f'(a)\), which telescopes across the entire interval.
Under a bounded fourth derivative this gives
Subtracting that boundary term gives a fourth-order corrected rule with exactly the same function samples, provided the endpoint slopes are known accurately. This argument also explains why the uncorrected trapezoid can be unusually accurate for a smooth periodic integrand: matching endpoint slopes sets the leading correction to zero without a special cancellation at each interior point. Matching values alone does not suffice if the periodic extension has a slope jump.
Account for both integration error and slope error
Integrate \(f(x)=x^4\) from zero to one with two equal panels. The three values are \(0,1/16,1\), so
The true integral is 0.2 and the endpoint derivative difference is four. Subtracting \((1/2)^2(4)/12=1/12\) gives \(19/96\approx0.1979167\). The corrected error is \(-1/480\). Its sign is now opposite to the original error; removing a leading term need not provide an upper bound for the remaining integral.
With four panels the trapezoid value becomes \(113/512\approx0.2207031\). Subtracting \(1/48\) gives about 0.1998698 and error \(-1/7680\). The error magnitude falls by sixteen, exactly the fourth-order factor in this polynomial example. The fourth derivative is constant, so the next terms that could disturb this ratio vanish. For a generic smooth function one would expect only an asymptotic approach toward sixteen.
Now suppose a noisy slope measurement makes the right endpoint derivative too large by 0.12 and the left one is exact. On the four-panel grid the corrected integral is displaced by an additional \(-h^2(0.12)/12=-0.000625\), larger than the discretisation error that remained with exact slopes. On a refinement series with that same systematic slope error, the ultimate error becomes second order once more. The theoretical gain therefore depends on the source and accuracy of the endpoint derivatives. Comparing the two error terms before commissioning derivative measurements gives a concrete sampling decision.
A separate possibility is to estimate the endpoint derivatives from nearby samples. To preserve a fourth-order global correction, the error in their difference should be of order \(h^2\) or smaller. A basic one-sided first difference normally has only first-order accuracy and can introduce an order-three term once multiplied by \(h^2\). A suitable higher-order one-sided approximation may repair that deterministic issue, but measurement noise is amplified when nearby noisy readings are subtracted and divided by their short spacing.
Change parameters · Composite quadrature and cancellation
Change one input at a time and compare the recalculated curves with the argument above. The browser evaluates this small model locally; the accompanying numerical values state its assumptions and reference checks. Reset restores the reference inputs, and the data can be downloaded as CSV.
Study the full derivation
Integrate the oscillations analytically and sample the envelope · Function approximation and numerical integration
A sensor model asks for many Fourier integrals of a slowly changing envelope. Direct trapezoids can return a full-scale signal where the true integral nearly cancels. Derive a Filon rule from exact oscillatory moments and find where it needs a different local model.