Chapter 1 · Piecewise interpolation and error bounds
Construct a continuous profile from sensor values, prove a local interpolation bound and distinguish sampling error from measurement uncertainty.
From first principles
Build a line from two measured endpoints
Suppose values \(y_0,y_1\) are known at \(x_0<x_1\) and no slopes are available. The simplest model reproducing both data is a line of constant slope. Let \(t\) denote the fraction of the panel traversed at the query point \(x\). Starting with the slope of the chord, rewrite the same line in terms of its endpoint weights:
Its weights are nonnegative on the panel and add to one, so constants and endpoint values are reproduced exactly. When the data come from a twice differentiable function with \(|f''|\le M\), curvature controls departure from the line. The two-node remainder gives
The last bound occurs at the midpoint. Halving panel width reduces this deterministic bound by a factor of four. Measurement errors in the endpoint values still enter through the interpolation weights and must be budgeted separately.
Derivation and applications
Balance curvature bias against uncertainty in interpolated readings
Consider a panel of length \(h=b-a\), with unknown smooth signal \(f\) and two independent noisy observations \(y_a=f(a)+\epsilon_a,\ y_b=f(b)+\epsilon_b\). Assume each error has zero mean and a known variance, and that \(|f''|\le M\) throughout the panel. For \(t=(x-a)/h\), linear interpolation gives the estimator \(\widehat f=(1-t)y_a+ty_b\). Its expectation follows simply by taking the expected value of each measured endpoint,
Independence eliminates the mixed error term when the noise contribution is squared. Consequently the noise variance depends on the interpolation location even on a flat signal,
Expanding the mean squared error about the estimator’s own expectation yields a sum of variance and squared bias. For equal endpoint standard deviations \(s\), the midpoint therefore satisfies
Grid refinement changes the second term, whereas independent repeat measurements at each endpoint reduce the first. Common-mode drift adds a covariance contribution that survives averaging between the two endpoints. In particular, an identical unknown offset passes unchanged through the interpolation because the weights sum to one.
Worked example
Determine which uncertainty dominates a midpoint
At two stations \(0.40\,\mathrm m\) apart the reading errors have \(s=0.030\,\mathrm K\), while \(M=0.50\,\mathrm{K/m^2}\). The maximum midpoint bias is \(0.010\,\mathrm K\) and the noise deviation is \(0.0212\,\mathrm K\). Their root-mean-square budget is
It is already dominated by reading noise.
Second application
Select a spacing from a root-mean-square target
For another instrument let \(s=0.020\), \(M=2.00\), and target midpoint root-mean-square error \(0.030\), in consistent units. The permitted bias magnitude is
Thus
If the noise were doubled at fixed error target, the remaining squared bias allowance would shrink to \(0.0001\).
Start from this chapter. For a convex quadratic, the chord lies above the curve. Predict the sign and size change of the midpoint error when each source interval is halved.
OneSimulation laboratory · Measure what interpolation does to a heat integral
Reconstruct from the information available
A line of thermometers supplies values \(y_i\) at increasing coordinates \(x_i\). It does not determine a unique continuous function: any function vanishing at every sensor can be added to a candidate profile. Choosing piecewise straight segments asserts that the unresolved curvature between consecutive readings is small enough for the intended measurement. This assumption may be excellent for predicting a mean temperature and poor for estimating a local heat flux, since differentiation increases the influence of measurement noise.
For \(x\in[x_i,x_{i+1}]\), let \(s=(x-x_i)/h_i\), where \(h_i=x_{i+1}-x_i>0\). The unique affine function matching both readings is \(I_hy=(1-s)y_i+sy_{i+1}\). It follows by writing an unknown intercept and slope, imposing the two endpoint values and eliminating both unknown coefficients. The weights are nonnegative and sum to one. The interpolated value lies between adjacent readings, constants are reproduced, and bounded additive errors of size \(\epsilon\) at the two sensors change the interpolant by at most \(\epsilon\). These properties can fail when extrapolating a considerable distance outside the measured interval.
Why the error is quadratic
Suppose \(f\) is twice continuously differentiable on a panel. Fix an interior point \(t\), and choose a coefficient \(c\) so that \(g(x)=f(x)-I_h f(x)-c(x-x_i)(x-x_{i+1})\) also vanishes at \(t\). It already vanishes at both panel endpoints. Rolle’s theorem applied twice gives a point \(\xi\) where \(g''(\xi)=0\). The interpolant has zero second derivative there, so \(c=f''(\xi)/2\). Evaluate the identity at \(t\) to obtain
The product is nonpositive within the interval and has greatest magnitude \(h_i^2/4\) at its midpoint. Thus the uniform error is at most \(h_i^2\max|f''|/8\). If every panel width is halved, an upper bound based on the same curvature falls by four. When curvature is positive, the segment overestimates the function. Knowledge of the curvature sign supplies information that an absolute error bound would discard.
Background · Can refining noisy samples make interpolation less useful?
Take the midpoint of two independent sensor readings with the same random error variance \(\sigma^2\). The midpoint interpolant averages those readings. Its variance is \(\sigma^2/2\), regardless of how close together the sensors stand. Meanwhile the size of the curvature bias is approximately \(|f''|h^2/8\). For a twice differentiable field with nearly constant curvature and unbiased readings, the midpoint mean squared error is approximately
Refining the sampling interval reduces the first term but leaves the second term. Once the two terms are comparable, repeat readings or a calibrated smoothing fit can improve a value estimate more efficiently. If both readings share the same offset, taking their average preserves that offset in full.
Turn the bound into a sampling decision
On the unit interval consider a temperature \(T=290+8x^2\) K, with \(x\) given numerically in metres. On the first panel of length 0.25 m the endpoint readings are 290 and 290.5 K. Their average is 290.25 K. The actual midpoint is 290.125 K, an overestimate of 0.125 K. The bound \(16(0.25)^2/8=0.125\) K is attained because the curvature is constant. A second panel of the same width has the same maximum interpolation error even though its temperature change is different.
Now allow an uncertainty of 0.03 K at every source node. A conservative total bound is \(2h^2+0.03\) K for \(h\) in metres. Achieving 0.05 K requires \(h\leq0.10\) m, or at least 11 measurements including both ends. No amount of interpolation onto a denser display grid changes this source requirement. For the slope, two readings with opposite errors can change the estimated derivative by \(2\epsilon/h\), which grows when \(h\) shrinks. Choosing sensor spacing therefore depends on the quantity to be estimated. A spacing suitable for accurate point values may require additional smoothing before slopes inferred from noisy data are useful.
Interpret a finite sensor footprint
Sometimes the observation is already a mean over a finite sensor footprint. For a symmetric footprint of width \(w\) centred at \(x\), the mean of a smooth field is \(f(x)+f''(x)w^2/24+O(w^4)\), by Taylor expansion and symmetry. For the quadratic temperature above this correction is exactly \(16w^2/24\) K when \(w\) is measured in metres. With a 0.10 m footprint it is about 0.0067 K above the point value. Interpreting a cell mean as a point reading therefore adds another positive bias before the chord interpolation even begins. This distinction becomes important when comparing a temperature probe with simulation values stored as cell averages.
Distribute measurements according to the curvature they must resolve
An equally spaced grid spends the same sampling budget in every part of a record. Suppose instead that the trajectory is twice continuously differentiable on each of several known regions, with a certified bound \(M_i\) for \(|f''|\) on region \(i\). Over a panel of width \(h_i\) the largest linear interpolation error is at most \(M_i h_i^2/8\). Thus keeping every local bound below a specified tolerance \(\epsilon\) requires \(h_i\le\sqrt{8\epsilon/M_i}\) whenever \(M_i>0\). A region with four times the curvature bound needs twice as many panels per unit length.
For a fixed total number of panels the reverse question is also helpful. In a region of length \(L_i\) with \(n_i\) equal panels its bound is \(M_iL_i^2/(8n_i^2)\). To minimise the largest such bound over positive continuous allocations, equalise those dominant local bounds. Otherwise moving some resolution from a region with a smaller bound to the largest can improve the maximum. The resulting allocation satisfies
Counts must then be rounded and their actual bounds checked. Known transitions in curvature should occur at grid nodes if each local bound is to apply to its entire panel.
Place nine panels across a changing acceleration
A displacement history lasts three seconds. In the first two seconds its acceleration magnitude is bounded by 2 m/s², and in the last second by 18 m/s². The relative panel allocations are
Nine panels cannot achieve exactly that ratio. Try four panels in the first interval and five in the second. Their widths are 0.5 and 0.2 s, giving error bounds \(2(0.5)^2/8=0.0625\) m and \(18(0.2)^2/8=0.0900\) m. Moving one panel to the late region instead gives bounds \(2(2/3)^2/8=0.1111\) m and \(18(1/6)^2/8=0.0625\) m. The four–five allocation has the smaller worst guarantee.
Nine equally spaced panels have width one third second throughout and include the transition at two seconds. Their late bound is 0.25 m, almost three times the nonuniform worst bound. This comparison is about a guaranteed maximum between observations, not only a discrepancy at selected test locations. Piecewise quadratic motions with constant accelerations attain the midpoint bound on each panel; slopes and positions can be matched at the transition without altering either local error.
The reasoning assumes acceleration bounds independent of the sampled readings. Estimating them from those same coarse readings can miss a short acceleration pulse entirely. If endpoint measurements also contain error bounded by 0.03 m, the convex interpolation weights add at most 0.03 m to each panel bound. The chosen allocation then certifies 0.12 m. Refining the grid further can reduce curvature error but cannot eliminate the measurement floor without better data.
If the allowable total error were 0.10 m, leaving 0.03 m for sensor uncertainty would allow at most 0.07 m for curvature. Four early panels already meet that condition. The late section would require at least six panels because \(18/(8\cdot6^2)=0.0625\), giving a ten-panel acquisition plan.
Where does a trustworthy interpolant cease to be accurate?
Interpolate the same smooth function on one interval with two and then three nodes. For the line the error changes with curvature, while for the quadratic the node product changes sign at the middle point. Inspect the signed error between observations.
![Where does a trustworthy interpolant cease to be accurate?. Horizontal axis: Position in [0, 1]. Vertical axis: Approximation minus exp(x). Data follow the figure.](/assets/worked-figures/approximation-and-quadrature/01-local-interpolation.png)
Read values from the plot
| Position in [0, 1] | Linear through endpoints | Quadratic through 0, 0.5, 1 |
|---|---|---|
| 0 | 0 | 4.4409e−16 |
| 0.25 | 0.14555 | −0.01227 |
| 0.5 | 0.21042 | 0 |
| 0.75 | 0.17171 | 0.013897 |
| 1 | 4.4409e−16 | 4.4409e−16 |
Change parameters · Where does a trustworthy interpolant cease to be accurate?
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
Approximating a resonance with a rational function · Function approximation and numerical integration
A smooth response on a measured interval can be governed by a nearby pole. Derive a low-order Padé fit, construct a barycentric rational approximant from samples and check whether a predicted pole survives independent data.
Chapter 2 · Polynomial interpolation and node placement
Derive the Lagrange interpolant, diagnose amplification of sample noise and use cosine-distributed nodes to control a polynomial error factor.
From first principles
Construct the unique interpolating polynomial
A polynomial of degree at most \(n\) has \(n+1\) coefficients. To interpolate \(n+1\) distinct abscissae \(x_i\), build one basis polynomial for each measurement. The factors \(x-x_j\) make it vanish at every other node; dividing by its value at \(x_i\) gives unit height there,
At \(x=x_i\) all terms except \(y_i\) disappear. Uniqueness follows because the difference of two such fits would have degree at most \(n\) and at least \(n+1\) distinct roots. The same representation also exposes sensitivity to equal bounded reading errors,
The sum depends on the node placement and the evaluation location. Distinctness ensures existence and uniqueness but gives no guarantee of uniformly small amplification at high degree.
Background · Interpolation condition
The polynomial matches the tabulated values at distinct nodes. Small nodal discrepancies do not guarantee a small error between nodes.
Derivation and applications
Derive barycentric weights from the node polynomial
Every cardinal basis polynomial contains nearly the same product of factors. Factoring out the common part leads to a practical evaluation formula. Assume \(n+1\) distinct real nodes and denote their monic node polynomial by \(L(x)=\prod_{i=0}^n(x-x_i)\). At a root \(x_i\) only one term in the derivative survives. Define a weight using that derivative,
For \(x\) away from the nodes, express the interpolant as \(L(x)\) times a rational sum. Apply the same formula to a polynomial identically equal to one, using the fact that interpolation reproduces constants. The two identities have the same factor \(L(x)\),
Their ratio cancels the product and gives the barycentric form
A common factor in the weights also cancels, allowing rescaling. At a node the individual terms have poles but the limit equals its stored datum; an implementation should return that datum directly on an exact match. The representation improves evaluation without repairing intrinsically poor node placement. If nodes are fixed and many observation sets arrive, their weights can be reused.
Worked example
Reconstruct a calibration at a new input
Use nodes \(0,1,3\), data \(2,1,5\), and common-scaled weights \((2,-3,1)\). At \(x=2\), the three terms in the denominator are \(1,-3,-1\); their data-weighted sum is \(2-3-5=-6\). Thus
Direct construction gives \(p(x)=x^2-2x+2\), confirming the reconstructed value.
Second application
Derive reusable weights for a different measurement grid
For nodes \(-1,0,1,2\), the four products \(L'(x_i)\) are \(-6,2,-2,6\). Multiplying all reciprocals by six gives weights \((-1,3,-3,1)\). At \(x=1/2\), the normalized interpolation weights reduce to \((-1,9,9,-1)/16\). An isolated unit error at the right endpoint changes this midpoint prediction by \(-1/16\), while a uniform shift of all readings by one moves the result by exactly one.
One polynomial through all measurements
Given \(n+1\) distinct nodes \(x_j\), seek one polynomial \(p\) of degree at most \(n\) matching \(y_j\) at each node. Define \(\ell_j(x)=\prod_{i\ne j}(x-x_i)/(x_j-x_i)\). This basis has value one at its own node and zero at all the others, so \(p=\sum_j y_j\ell_j\) satisfies the observations. If another such polynomial existed, the difference would have \(n+1\) separate zeros despite degree at most \(n\). It must vanish identically. Uniqueness concerns exact arithmetic and says little by itself about sensitivity.
For the nodes \(-1,0,1\), the three basis functions are \(x(x-1)/2,\ 1-x^2,\ x(x+1)/2\). At \(x=1/2\) their values are \(-1/8,3/4,3/8\). They sum to one but are not all positive. Consider samples \(2,1,2\): the predicted value is \(1.25\), consistent with the quadratic \(1+x^2\). If the three readings instead carry independent signed perturbations bounded by \(\epsilon\), the possible prediction error at this point reaches
The worst perturbation takes signs matching those of the basis values.
Separate noise and approximation
The maximum of \(\sum_j|\ell_j(x)|\) over the interval, the Lebesgue constant, bounds the operator’s amplification of data errors. A different quantity controls the error of interpolation from exact samples. For sufficiently smooth \(f\), repeating the Rolle argument with \(n+2\) zeros gives
This formula compares the exact function with the selected polynomial. It contains both a geometric factor controlled by the nodes and a higher derivative that may grow quickly with degree. A small geometric factor cannot by itself establish convergence for an arbitrary function.
On \([-1,1]\) let \(T_m(x)=\cos(m\arccos x)\). From the cosine addition formula, \(T_{m+1}=2xT_m-T_{m-1}\) with \(T_0=1,T_1=x\). Thus \(T_m\) is a polynomial of degree \(m\) with leading coefficient \(2^{m-1}\) for \(m\geq1\). Its \(m\) zeros lie at \(\cos[(2k+1)\pi/(2m)]\). Choosing them as interpolation nodes makes the monic geometric factor \(2^{1-m}T_m(x)\), whose maximum magnitude is exactly \(2^{1-m}\).
Why the alternating extrema matter
At the \(m+1\) points \(\cos(k\pi/m)\), this monic factor alternates between its positive and negative extreme. Suppose another monic degree-\(m\) polynomial had a strictly smaller maximum magnitude. Subtract it from the Chebyshev factor. The leading powers cancel, leaving degree at most \(m-1\). At the successive extrema the difference must alternate in sign, forcing at least \(m\) distinct zeros between them. That contradicts its degree. This minimax argument concerns the node polynomial, and explains the deliberate concentration of nodes near the endpoints.
For \(m=3\) the recommended points are \(0,\pm\sqrt3/2\); their monic factor is \(x^3-3x/4\) with magnitude at most 0.25. The equally spaced alternative \(-1,0,1\) has factor \(x^3-x\), whose largest magnitude is
If data already exist at fixed locations, moving them is seldom an option. Subdividing the interval and fitting lower-degree polynomials locally instead limits long-range coupling. For evaluation at many points, barycentric interpolation can reuse stored node weights while avoiding explicit construction of a large monomial coefficient vector.

Predict the degree from the nearest complex singularity
Well-chosen nodes control amplification of data errors. The rate at which a smooth target itself can be approximated also depends on what happens away from the real interval. Write \(x=(z+z^{-1})/2\). The unit circle maps to \([-1,1]\), and the circle \(|z|=\rho>1\) maps to an ellipse with foci at the endpoints. The Chebyshev polynomial obeys \(T_k(x)=(z^k+z^{-k})/2\). Consequently the Laurent coefficients of \(f((z+z^{-1})/2)\) determine the Chebyshev coefficients of \(f\). If the function extends analytically through the closed ellipse and has magnitude at most \(M\) there, the Cauchy coefficient bound gives \(|a_k|\le2M\rho^{-k}\) for \(k\ge1\). Summing this geometric tail bounds the error of the degree-\(n\) truncated series by \(2M\rho^{-n}/(\rho-1)\) on the interval. A real-axis corner invalidates this analytic argument.
A rational response with an exactly measurable tail
For \(0<q<1\), take \(f(x)=(1-q^2)/(1-2qx+q^2)\). With \(x=\cos\theta\), summing the two geometric series in \(qe^{\pm i\theta}\) gives
Its pole at \(x=(q+q^{-1})/2\) lies on the ellipse with parameter \(1/q\). The exact coefficients decay like \(q^k\). At \(x=1\) all omitted terms have the same positive sign. Since \(|T_k|\le1\), the uniform truncation error equals \(2q^{n+1}/(1-q)\).
For \(q=1/3\) the pole is at \(5/3\), and the error equals \(3^{-n}\). Degree six leaves error \(1/729\approx0.00137\). Degree seven reduces it to \(1/2187\approx0.000457\). This establishes a degree for a specified error before constructing a node grid. These exact errors concern the truncated series. An interpolant fitted on Chebyshev nodes combines unresolved modes into lower coefficients and need not have precisely the same error, although analyticity still gives geometric convergence.
Practise on sheet 1 · How close can a pole move before the degree budget fails?. Further reading · University of Oxford · Chebyshev Series, Nick Trefethen · Lecture 3, Chebyshev series, part 2, Smoothness and convergence theorems.
Evaluate without forming monomial coefficients
Define barycentric weights \(w_j=1/\prod_{i\ne j}(x_j-x_i)\). Dividing the Lagrange interpolation formula and the identity \(\sum\ell_j=1\) by the common nodal polynomial gives the evaluation ratio \(\sum_j w_j y_j/(x-x_j)\) divided by \(\sum_j w_j/(x-x_j)\). At an exact interpolation node, return its stored value directly. Multiplying all weights by the same constant has no effect, which is useful for numerical scaling.
For nodes \(-1,0,1\) the weights are proportional to \(1,-2,1\). At \(x=1/2\) with data \(2,1,2\), the weighted numerator is \(4/3-4-4=-20/3\), and the denominator is
Their ratio gives 1.25. This evaluates the very same polynomial as the basis construction. Better arithmetic for evaluation cannot remove an intrinsically large Lebesgue constant associated with a poor set of nodes.
Determine exactly how node errors can reinforce
For fixed distinct interpolation nodes let \(L_j(x)\) denote the cardinal polynomials. Changing the readings by errors \(e_j\) changes a reconstructed value by \(\sum_j e_j L_j(x)\). With independent bounds \(|e_j|\le\delta\), taking absolute values gives an amplification no larger than \(\delta\sum_j|L_j(x)|\). At any fixed evaluation point this bound can be attained by choosing the sign of \(e_j\) to agree with the sign of \(L_j(x)\). The sum of absolute cardinal values is therefore the exact pointwise error amplification for this particular error model.
If all reading errors are a single unknown constant instead, the amplification is exactly one because the cardinal polynomials sum to one. The same nodes have different noise behaviour for coherent offsets and independent bounded perturbations. Statistical independence with equal variances provides a third measure: the output variance is \(\sigma^2\sum_jL_j(x)^2\). The worst pointwise absolute sum, its maximum across the interval, and this root-sum-of-squares factor should not be interchanged. They correspond to questions about adversarial signs, location and probabilistic noise, respectively.
Check a three-station calibration inside and beyond its range
Take stations at \(-1,0,1\). Their cardinal polynomials are \(x(x-1)/2,\ 1-x^2,\ x(x+1)/2\). At \(x=1/2\) they take values \((-1/8,3/4,3/8)\). The weights sum to one, but their absolute values sum to \(5/4\). If each observation is accurate to within 0.02 units, the interpolated calibration can be wrong by 0.025 from observations alone. The specific error pattern \((-0.02,0.02,0.02)\) attains that value. Polynomial exactness for noise-free quadratic inputs provides no protection against that sign pattern.
With independent standard deviations 0.02, the same evaluation instead has standard deviation \(0.02\sqrt{1/64+9/16+9/64}=0.02\sqrt{46}/8\approx0.01696\). The smaller value follows from the assumed random cancellation and is not a guaranteed bound. At \(x=2\), beyond the calibration interval, the same weights become \(1,-3,3\). The worst bounded measurement error is now \(7(0.02)=0.14\). Every tabulated station can pass a calibration check while extrapolation is seven times more sensitive than an original reading.
Inside \([0,1]\) the absolute sum simplifies to \(1+x-x^2\); its maximum occurs at one half and equals \(5/4\). Symmetry gives the same maximum on the other half. For quadratic interpolation this gives a complete guarantee throughout the stated interval, with construction of the worst perturbation. A graph of the fitted polynomial itself would reveal none of these conditioning facts. A sensor specification therefore needs both an admissible evaluation range and a description of how the raw station errors may vary together.
The maximum amplification also gives a way to compare retrospective calibrations. If a process must meet a total error of 0.03 units and each raw persistent bounded error may be as large as 0.02, the three-point design leaves at most \(0.03-1.25(0.02)=0.005\) units for polynomial approximation bias throughout the interval. A check at the three stations themselves would assign a larger remaining allowance and would miss the interior maximum.
Change parameters · Polynomial interpolation and node placement
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
Integrating cosine interpolants on nested grids · Function approximation and numerical integration
Chebyshev points turn polynomial interpolation into a cosine series. Derive the exact moments of each basis polynomial, explain aliasing and find a case where two consecutive quadrature grids confidently agree on the wrong answer.
Problem sheet 1 · Nodes and interpolation
Analyse local interpolation errors, demonstrate noise amplification under extrapolation and compare two sets of global interpolation nodes.
Estimate a probe requirement
A smooth pressure profile on a 2 m pipe satisfies \(|p''|\leq24\) kPa/m². Each probe has absolute uncertainty 0.01 kPa. Bound the total error of piecewise linear interpolation. Find the largest equal spacing consistent with 0.04 kPa total error and the smallest number of probes including the two endpoints.
Worked solution
Between measured nodes the interpolation error of exact samples is bounded by \(24h^2/8=3h^2\) kPa. The two sample errors enter with nonnegative weights summing to one, adding at most 0.01 kPa. The requirement \(3h^2+0.01\leq0.04\) gives \(h\leq0.10\) m. Twenty intervals on a 2 m pipe require 21 probes.
This calculation controls worst-case pressure values and assumes the curvature estimate holds on every panel. A single unnoticed discontinuity would invalidate its use on that panel.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Predict beyond the sensors
Two sensors at positions 0 and 1 m each have error at most 0.5 K. Compute the interpolation weights at 0.4 m and the extrapolation weights at 1.5 m. Find the largest change to each predicted temperature and provide a sign pattern attaining each bound.
Worked solution
At 0.4 the weights are 0.6 and 0.4. Equal positive errors produce the worst-case rise of 0.5 K. At 1.5 the weights are \(-0.5\) and \(1.5\). Taking the first error negative and the second positive yields
Even for a perfectly affine true profile the second estimate is more sensitive to data noise. If the true profile is curved, extrapolation adds an entirely separate approximation error.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Construct a minimax nodal factor
Choose two symmetric nodes \(\pm c\) on \([-1,1]\). Find the maximum magnitude of their monic nodal polynomial and minimise it over \(0\leq c\leq1\). Use the result to bound the interpolation error when \(|f''|\leq4\).
Worked solution
The nodal polynomial is \(x^2-c^2\); its negative extreme is \(-c^2\) at zero and positive extremes occur at the endpoints with value \(1-c^2\). Thus its norm is \(\max(c^2,1-c^2)\), minimised at \(c^2=1/2\). The nodes are \(\pm1/\sqrt2\) and the best monic norm is \(1/2\).
The Lagrange remainder yields maximum error at most \(4(1/2)/2=1\). For endpoints as nodes the same reasoning gives a bound of 2. The change improves this worst-case bound even though the endpoint readings themselves are no longer sampled.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
How close can a pole move before the degree budget fails?
For the same rational family, a changed physical parameter gives \(q=1/2\). Locate the pole and find the smallest truncation degree giving uniform error at most 0.002. Compare with \(q=1/3\) at that tolerance. Explain why increasing the density of a plot cannot establish a smaller worst-case error than the derived tail.
Worked solution
The pole is \((1/2+2)/2=1.25\), closer to the interval than \(5/3\). The exact tail is \(2^{1-n}\). At degree nine it is \(1/256\approx0.00391\). At ten it is \(1/512\approx0.00195\). Thus ten is the first sufficient degree.
For \(q=1/3\), degrees five and six give \(1/243\) and \(1/729\), so six suffices. The four extra degrees are explained by the slower coefficient decay. The endpoint \(x=1\) attains the tail exactly, regardless of how densely interior points are plotted.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Revisit chapter 2 · Predict the degree from the nearest complex singularity.
Chapter 3 · Hermite pieces and cubic splines
Build a cubic from endpoint values and slopes, then determine missing curvature information by joining adjacent pieces smoothly.
From first principles
Determine a cubic from endpoint values and slopes
On one panel \([a,b]\), approximate a smooth curve with a cubic and use both endpoint heights and slopes. Let \(h=b-a>0\), \(t=(x-a)/h\), endpoint heights \(y_0,y_1\), and derivatives \(d_0,d_1\) with respect to \(x\). The conditions at the left endpoint immediately fix two coefficients,
The factor \(h\) converts a derivative per unit \(x\) into one per unit \(t\). Write \(\Delta=y_1-y_0\). Imposing the right endpoint value and derivative gives two linear equations,
Solving gives
Thus four measurements determine four coefficients uniquely. Adjacent panels sharing heights and slopes join with a continuous first derivative. If only heights are measured, a spline construction supplies the missing information through smoothness conditions between panels and boundary conditions at the ends.
Derivation and applications
Check whether a cubic panel preserves a rising signal
A cubic matching two heights and slopes can overshoot even when both endpoint heights increase. Consider a Hermite panel with \(y_1>y_0\), length \(h\), slope of the chord \(m=(y_1-y_0)/h\), and endpoint derivatives \(d_0,d_1\). The derivative of the cubic is a quadratic. Express that derivative using the nonnegative Bernstein basis on \(0\le t\le1\),
Here \(p'\) is with respect to the physical coordinate \(x\). The first and last coefficients enforce the endpoint derivatives. Each of the three basis functions has integral \(1/3\) over \(t\). Since integrating \(p'(x)\) across the physical panel must return the specified height gain, the middle coefficient is fixed,
Nonnegative coefficients provide a simple sufficient condition for a nondecreasing panel. The basis functions also sum to one, so they immediately bound the derivative when the condition holds,
A negative middle coefficient alone does not prove reversal, since the three basis functions overlap. If the sufficient test fails, evaluate the minimum of the quadratic on the panel, including its endpoints and any interior stationary point. Local monotonicity matters when interpolating cumulative counts or instrument calibrations that must be invertible.
Worked example
Certify a rising calibration between samples
A signal rises from 2 to 5 over \(h=2\), so \(m=1.5\). Reported slopes are \(d_0=1\) and \(d_1=3\), giving \(b=0.5\). The derivative is nonnegative everywhere. At the midpoint it equals
No hidden local maximum can lie inside this panel.
Second application
Find a reversal that endpoint slopes conceal
On a separate unit panel take a rise of one and equal endpoint slopes of four. Then \(m=1\), \(b=3-8=-5\), and the midpoint derivative is
Both measured endpoint derivatives are positive, yet the fitted curve locally decreases. Replacing both slopes by \(1.5\) gives \(b=0\) and restores a certifiably nondecreasing interpolation while preserving the two measured heights.
Four conditions on a single panel
Line segments reproduce values but change slope abruptly at a sensor. A trajectory planner may require a smooth velocity as well as an accurate position. On a panel of width \(h\) let \(s=(x-x_i)/h\). A cubic polynomial has four coefficients. Specifying \(y_i,y_{i+1}\) and slopes \(d_i,d_{i+1}\) determines it uniquely. A convenient basis writes the interpolant as
To reconstruct these terms, seek a cubic multiplying \(y_i\) with value one at \(s=0\), zero at \(s=1\), and zero slope at both ends. The four linear conditions give \(2s^3-3s^2+1\). The other basis functions follow by imposing a unit on their own datum and zero on the remaining three. The factors of \(h\) convert derivatives with respect to physical \(x\) into derivatives with respect to dimensionless \(s\). Dropping these factors would make the interpolant change shape when switching between metres and centimetres.
For positions \(y_0=0,y_1=1\) m over one second with both endpoint velocities zero, \(H=3s^2-2s^3\) m. At half time the position is 0.5 m but the speed is 1.5 m/s, greater than the mean speed of 1 m/s. Imposing rest at both ends forces the intervening speed to exceed the mean somewhere. The piece alone leaves endpoint accelerations \(+6\) and \(-6\) m/s². A smooth join to a subsequent segment therefore needs more than identical endpoint positions.
Recover slopes when only values are measured
A cubic spline fits one cubic on every interval, requiring continuity of both first and second derivatives at interior nodes. Let \(M_i=S''(x_i)\). Since a cubic has a linear second derivative, on panel \(i\) interpolate \(M_i\) and \(M_{i+1}\) linearly and integrate twice. Use the two measured endpoint values to fix the integration constants. On equal panels the resulting right-hand slope at the left endpoint is \((y_{i+1}-y_i)/h-h(2M_i+M_{i+1})/6\). The left-hand slope at the right endpoint is \((y_{i+1}-y_i)/h+h(M_i+2M_{i+1})/6\).
Equating these expressions at an interior join gives
This tridiagonal system relates each undetermined curvature to the neighbouring data. Two additional end conditions are needed. A natural spline imposes zero curvature at both endpoints. A clamped spline uses given endpoint slopes instead. Choose those conditions from what the experiment actually controls.
Examine the influence of endpoint assumptions
Fit a natural spline at \(x=0,1,2\) to \(y=0,1,0\). The end curvatures are zero and the interior equation gives \(4M_1=6(0-2+0)=-12\), hence \(M_1=-3\). On the first panel \(S''=-3x\). Two integrations give
The endpoint values set \(b=0,a=1.5\), yielding \(S(0.5)=0.6875\) compared with 0.5 from the straight chord. Symmetry gives zero slope at the summit and a reflected cubic on the second interval.
Smoothness alone cannot establish the true midpoint value. A sensor measuring a sharp corner would support a piecewise linear description, and monotone data can require a slope limiter to avoid artificial extrema in a cubic fit. Likewise, setting endpoint curvature to zero in a mechanical fit asserts a moment condition only under the appropriate beam model. Report the end conditions with the fitted curve, especially when derivatives near the ends are used as physical observables.
Use independent endpoint information as a check
Suppose the three displacement values in the example come with an independent measurement of the initial slope, \(S'(0)=1\) rather than 1.5. Imposing a natural left endpoint as well as this slope would overdetermine that end. One reasonable choice is a mixed spline, clamped on the left and natural on the right. For \(h=1\), the slope formula at the left reads \(1-(2M_0+M_1)/6=1\), giving \(2M_0+M_1=0\). The interior equation gives \(M_0+4M_1=-12\), since \(M_2=0\).
Solving yields \(M_1=-24/7\) and \(M_0=12/7\). A measured slope at one end has changed curvatures inside the interval. That coupling across segments distinguishes a global spline fit from interpolating each segment independently with prescribed slopes at every node.
Why the natural spline minimises bending
Consider all twice continuously differentiable interpolants of the same tabulated values on an interval. For a natural cubic spline \(S\), each panel is cubic, \(S'\) and \(S''\) agree across knots, and \(S''=0\) at both endpoints. Let a competing interpolant be \(S+w\). The perturbation \(w\) vanishes at every knot including the endpoints. Expanding the squared curvature integral gives
To prove that \(S\) minimises this integral, account for every boundary term in the cross product.
Integrate the cross product by parts twice on each panel. The interior integral containing \(S''''w\) vanishes because the panel is cubic. The term \(S'''w\) vanishes at every panel endpoint since \(w=0\) at each knot. The remaining interface contributions \(S''w'\) cancel between adjacent panels because both factors are continuous. At the outer boundaries \(S''=0\). Thus the cross term vanishes exactly. Equality of the objectives requires \(w''=0\) throughout; a globally affine perturbation vanishing at two distinct knots is zero. This proves uniqueness within the admissible class and explains the natural endpoint condition as part of a variational statement.
Calculate the bending energy on an uneven grid
Suppose the interpolation points are \((0,0),(1,2),(3,2)\). The panel widths are one and two, and the secant slopes are two and zero. For a natural cubic write \(M_i=S''(x_i)\), so
Continuity of first derivative at the central knot gives \(2(1+2)M_1=6(0-2)\), hence \(M_1=-2\). The bending moment changes linearly from zero to −2 on the first panel and from −2 to zero on the second. The longer panel contains twice the squared curvature integral because it sweeps the same range of curvature over twice the distance.
Specifically the first contribution is
On the second panel \(S''=x-3\), giving \(\int_1^3(x-3)^2dx=8/3\). Total energy is four. Integrating the first curvature twice and fitting its endpoints gives
at the central knot the slope is \(4/3\), neither of the adjacent straight-line secant slopes. On the second panel write \(t=x-1\). Then \(S=2+4t/3-t^2+t^3/6\), which returns to two at \(t=2\). The curve rises above the equal second and third data values in between.
Minimum bending therefore does not guarantee monotonicity between nearly flat measurements or an absence of overshoot. If flat endpoints describe a known plateau rather than merely two equal observations, a shape constraint changes the admissible functions. The preceding proof still explains why the natural interpolant won its own curvature competition, but gives no reason to prefer it after physical constraints have changed.
For these data the overshoot can even be located analytically. On the second panel the derivative vanishes when \(4/3-2t+t^2/2=0\), giving the interior root \(t=2-2/\sqrt3\), about 0.845. A measured value taken near \(x=1.845\) would therefore help discriminate the minimum-bending curve from a physical plateau. Taking another measurement at either already constrained endpoint would do less to resolve that ambiguity.
Can an interpolated cumulative reading decrease?
A monotonically increasing quantity is sampled at integer times 0 through 4 with values 0, 0.04, 0.08, 1, 1. A natural spline enforces continuous second derivative and zero end curvature. A shape-preserving cubic constrains the node slopes.

Read values from the plot
| Time (s) | Natural cubic spline | Shape-preserving cubic | Piecewise linear |
|---|---|---|---|
| 0 | 0 | 0 | 0 |
| 1 | 0.04 | 0.04 | 0.04 |
| 2 | 0.08 | 0.08 | 0.08 |
| 3 | 1 | 1 | 1 |
| 4 | 1 | 1 | 1 |
Change parameters · Can an interpolated cumulative reading decrease?
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.
Chapter 4 · Composite quadrature and cancellation
Derive midpoint, trapezoidal and Simpson formulas, and use the sign of curvature to interpret a pair of numerical integral estimates.
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.
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.
OneSimulation laboratory · Measure what interpolation does to a heat integral
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.
Problem sheet 2 · Smooth pieces and integrated loads
Build a constrained trajectory, infer a spline curvature, and check quadrature by energy conservation over a measured interval.
Connect two resting positions
A carriage moves from 0 to 4 m in two seconds, starting and finishing at rest. Find the unique cubic trajectory satisfying these four endpoint data. Determine midpoint speed and the two endpoint accelerations. Can this cubic join a stationary segment with continuous acceleration?
Worked solution
With \(s=t/2\) the trajectory is \(4(3s^2-2s^3)\). Differentiating with respect to time gives \(v=12s(1-s)\) m/s, so \(v(1\ {\rm s})=3\) m/s. Acceleration is \(6(1-2s)\) m/s², giving \(+6\) and \(-6\) at the endpoints.
The velocity can join rest continuously. The stationary segment has zero acceleration, so this particular cubic cannot also give a continuous acceleration there. Enforcing both endpoint accelerations adds two constraints, motivating a higher-degree segment.
Explore the related calculation with adjustable inputs. Vary a slope or endpoint value and examine how an interpolant changes between observations. Map this exercise’s interval to the unit interval before comparing the basis functions.
Identify what a natural endpoint buys
At \(x=0,1,2\) a rod has displacements \(0,2,0\). Construct the first segment of the natural cubic spline and find its slope at 0 and its value at 0.5. Compare with the quadratic through all three data.
Worked solution
The natural curvatures are
The interior equation gives \(4M_1=6(0-4+0)=-24\), so \(M_1=-6\). Integrate \(S''=-6x\) and impose the first two values to get
The initial slope is 3 and midpoint value 1.375.
The global quadratic is \(4x-2x^2\), with initial slope 4 and midpoint value 1.5. Both match every measured value. The difference is detectable in unmeasured derivatives and in the interior prediction because the quadratic has nonzero end curvature.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Recover a missing quadratic load
On a unit-width panel a power signal is quadratic. Its endpoint values are 2 W and 6 W; its measured energy over one second is 3 W·s. Infer its midpoint value, compare the midpoint and trapezoidal estimates, and determine the sign of curvature.
Worked solution
Simpson integrates the quadratic exactly, so \(3=(2+4P_m+6)/6\), giving \(P_m=2.5\) W. The midpoint estimate is 2.5 J and the trapezoidal estimate is 4 J. Their weighted combination \((2\cdot2.5+4)/3=3\) J reproduces the measured energy.
The signal midpoint lies below the endpoint chord value 4 W, so the curvature is positive. These conclusions use the stipulated quadratic law; the same three observations cannot uniquely determine an arbitrary power history.
Explore the related calculation with adjustable inputs. Compare errors from common-node composite rules; the explorer uses an exponential reference, while the polynomial identities in this exercise can be checked exactly.
Does three-level extrapolation integrate every smooth input exactly?
For \(f(x)=x^6\) on \([0,1]\), the trapezoids with one, two and four panels are \(1/2,\ 33/128,\ 1421/8192\). Compute the two first-column corrections and the final diagonal value. Compare it with the exact integral and identify the first uncancelled error power.
Worked solution
Removing the quadratic terms gives
Removing the quartic term gives
The exact value is \(1/7\), so the excess is \(1/2688\). Both cancellations were exact algebraically, but the trapezoid expansion for this polynomial also contains an \(h^6\) term. Three grids remove two independent error coefficients. Exact integration of every smooth function cannot follow from that finite information.
Explore the related calculation with adjustable inputs. Compare trapezoidal and extrapolated estimates as the power of the integrand changes; track when the smooth-error expansion needed for cancellation is valid.
Revisit chapter 4 · Build a Romberg table from nested panels.
Recover an integral using two biased readings
The four- and eight-interval integrals of the quadratic profile are 306.875 and 306.71875 K·m. Assume their leading error is \(Ch^2\). Eliminate \(C\) to estimate the integral and predict the sixteen-interval output. Explain why this elimination is exact for this model on uniform grids but needs a refinement check for arbitrary data.
Work through the solution
Write \(I_h=I+Ch^2\) and \(I_{h/2}=I+Ch^2/4\). Subtract the first relation from four times the second to get \(I=(4I_{h/2}-I_h)/3=306.66667\) K·m. The eight-interval bias is 0.0520833 K·m. Dividing by four gives a sixteen-interval prediction of 306.67969 K·m. Constant curvature makes the trapezoidal error exactly proportional to \(h^2\) for this quadratic. Curvature variation, lack of smoothness or measurement noise can spoil the assumed ratio.
Chapter 5 · Gaussian quadrature and exactness
Choose quadrature nodes from moment conditions, prove the polynomial exactness of Gauss rules and map a reference rule to a finite element.
From first principles
Choose quadrature nodes by matching moments
A quadrature formula can be designed by asking it to reproduce integrals of successive monomials. On \([-1,1]\), take two nodes at \(\pm a\) with equal weight \(w\), exploiting reflection symmetry of the interval and uniform measure. This model integrates every odd polynomial exactly because its two sampled values cancel. Exactness for the constant and quadratic terms requires
The equations give \(w=1\) and \(a=1/\sqrt3\). By linearity the resulting two-point Gauss rule is exact for every cubic polynomial,
Its nodes lie inside the interval, making it useful when endpoints are expensive or shared information is unavailable. Higher-degree accuracy for an arbitrary function depends on the size of the unresolved part of its shape. Mapping another interval affinely requires scaling both the nodes and the weights by the appropriate coordinate transformation.
Background · Quadrature degree
Exactness through degree d is an algebraic property. For a nonsmooth or poorly sampled integrand the observed rate can be much lower.
Derivation and applications
Derive a two-point rule when one endpoint must be sampled
Suppose a measurement at one endpoint is already required for another purpose. How much polynomial exactness remains if the second sample can be placed freely? On \([0,1]\), fix the first node at zero and place the second at \(a\). Denote their weights \(w_0,w_1\). Exact integration of the first three monomials requires
Dividing the quadratic condition by the linear one determines \(a=2/3\); back-substitution fixes both weights. This is the two-node left Gauss–Radau rule. Its first missed monomial can be computed directly,
To see what determines the sign of the error for a more general function, interpolate with a quadratic that matches \(f\) at zero and matches both \(f\) and its derivative at the interior node. The quadrature sees the same values as that quadratic, which it integrates exactly. For a function with continuous third derivative the interpolation remainder has a factor \(x(x-2/3)^2\), nonnegative over the interval. Integrating and applying the weighted mean value theorem gives
A convexity assumption alone does not determine the sign here, since the error depends on the third derivative. Scaling the panel length by \(h\) multiplies the third-derivative error coefficient by \(h^4\).
Worked example
Integrate a profile on a physical interval
On \(0\le t\le3\) let a flow rate be \(q(t)=2+t^2\) in consistent units. The Radau nodes are \(0\) and \(2\), and the integral is
Direct integration gives \(6+9=15\). The freely chosen interior station resolves quadratic curvature using only one new measurement.
Second application
Bound the error for a rising exponential
On \([0,1]\) the rule gives \(Q(e^x)=0.25+0.75e^{2/3}=1.71080\), compared with \(e-1=1.71828\). Its error \(0.00748\) is positive. Since \(1\le f'''\le e\), the derived bound brackets the error between \(1/216=0.00463\) and \(e/216=0.0126\), consistent with the direct result.
Three nodes sampling a Gaussian ensemble
An ensemble has normalised density \(p(x)=e^{-x^2}/\sqrt{\pi}\) over the real line. An instrument records the mean of \(\cos(\omega x)\). Its effective response changes from a slowly varying function to a rapidly oscillating one as \(\omega\) increases. Build a quadrature rule that samples the ensemble only three times. The aim is to learn what exactness for polynomials implies for an observable with a variable frequency.
Exploit symmetry and put nodes at \(-c,0,c\), with equal outer weights \(w\) and central weight \(1-2w\). Odd moments vanish automatically. Integration by parts using \(p'(x)=-2xp(x)\) gives ensemble second and fourth moments \(1/2\) and \(3/4\). Matching them imposes \(2wc^2=1/2\) and \(2wc^4=3/4\). Divide the equations to find \(c^2=3/2\). Substitution gives \(w=1/6\), hence central weight \(2/3\). This proves exactness through degree five without needing a table of Gauss–Hermite nodes.
For the instrument response the three readings give
For comparison derive the exact transform \(I(\omega)=\int p(x)\cos(\omega x)\,dx\). Differentiating under the integral and once integrating by parts using the derivative of the Gaussian gives
with \(I(0)=1\). Hence \(I=\exp(-\omega^2/4)\). This independent answer tests the numerical method in the transition from well-resolved response to nearly complete cancellation.
Open full-size diagramExpand the cosine in even powers near zero. Its constant, quadratic and quartic terms are integrated exactly. The first possible error has order \(\omega^6\); the sixth ensemble moment is \(15/8\), while the rule produces \(9/8\). The difference begins as \(Q-I=\omega^6/960+O(\omega^8)\). This is a local frequency statement. At high frequency the exact response tends to zero, but the discrete sum repeatedly returns to one. Increasing the node count extends the useful frequency range, as the notebook's independent 64-node comparison illustrates.
A sensor that records only these three phase samples cannot distinguish a large carrier with phases differing by integer multiples of a full cycle from zero carrier at the sampling nodes. This is a property of the information supplied to the quadrature, not a failure of the root-finding procedure that produced the nodes. A useful extra observation would be at a coordinate whose phase differs for the two suspected frequencies; merely repeating a measurement at the central node cannot resolve them.
The Gaussian weight in this example has variance one half. If a laboratory reports a Gaussian standard deviation \(\sigma\) in physical units, first set the physical coordinate to \(\sqrt{2}\sigma x\). The carrier in the dimensionless quadrature then becomes \(\sqrt{2}\sigma\omega_{\rm physical}\). Scaling the nodes without scaling the frequency in the reference calculation would compare two different instruments.
Find a nonzero frequency at which all three individual measurements return exactly one and calculate the true ensemble mean there.
Work through the solution
Choose \(\omega=2\pi/c\). Then \(\omega c=2\pi\), so both outer cosines and the central cosine equal one. The true mean is
The error here is large despite exactness for five polynomial degrees; the integrand's scale has changed relative to the chosen sampling nodes.
Change parameters · Explore this notebook example
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.
Spend samples where they are most useful
When the integrand is a callable function, quadrature nodes need not coincide with pre-existing sensors. A rule with \(n\) distinct nodes and \(n\) weights has \(2n\) scalar parameters. Can these integrate every polynomial through degree \(2n-1\)? Merely counting parameters does not prove existence. The Gauss construction supplies nodes for a positive weight function on an interval and establishes the exactness by orthogonality.
Start on \([-1,1]\) with a symmetric two-node rule of the form \(w[f(-c)+f(c)]\). Testing the constant function gives \(2w=2\), hence \(w=1\). Symmetry automatically integrates the odd monomials \(x,x^3\). Testing \(x^2\) gives \(2c^2=2/3\), or \(c=1/\sqrt3\). These four independent moment conditions establish exactness on every cubic by linearity. Testing \(x^4\) produces \(2/9\), whereas its integral is \(2/5\). The error appears at degree four exactly as the parameter count suggested.
Prove the general degree claim
Let \(P_n\) be the degree-\(n\) orthogonal polynomial for the prescribed positive integration weight \(w(x)\). Use its \(n\) distinct interior zeros as nodes. Define the weights by integrating the Lagrange basis on these nodes, so every polynomial of degree at most \(n-1\) is already integrated exactly. To treat any polynomial \(f\) of degree at most \(2n-1\), divide it by \(P_n\), giving \(f=P_n q+r\) with \(\deg q,\deg r\leq n-1\).
The integral of \(P_nq\) vanishes by orthogonality, and every quadrature evaluation of that product vanishes because the nodes are zeros of \(P_n\). Both the integral and the rule therefore reduce to the same value for \(r\). This proves exactness. There is a sharp obstruction to one extra degree: \(P_n^2\) is nonnegative, positive except at finitely many points, and all its sampled values vanish. Its positive integral cannot be reproduced by this rule. Positivity of the individual Gauss weights follows by applying exactness to the square of each Lagrange basis polynomial.
Transfer the rule into a physical element
An element \([a,b]\) is obtained by the affine change \(x=m+\ell \xi\), with midpoint \(m=(a+b)/2\), half-length \(\ell=(b-a)/2\), and \(dx=\ell\,d\xi\). Both the node locations and their weights change. For \([2,4]\), the two physical nodes are \(3\pm1/\sqrt3\), with unit physical weights. The integral of \(x^3\) is
Summing the nodal cubes gives
A missing Jacobian would escape detection on this particular element where \(\ell=1\); test a second element of a different length.
In a linear finite element with constant density, each consistent mass entry integrates a product of two linear basis functions, hence a quadratic. Two Gauss points integrate it exactly. On a unit element the true mass matrix has diagonal \(1/3\) and off-diagonal \(1/6\). Using just the midpoint makes all four entries \(1/4\). The alternating nodal vector \((1,-1)^T\) then has zero discrete mass although its interpolated field has a positive squared integral. This loss of a mode is a practical consequence of insufficient quadrature. With curved mappings or varying coefficients, determine the degree and smoothness of the entire transformed integrand before reusing a quadrature order.
Distinguish a load integral from a stiffness integral
On the same unit element, a constant axial stiffness integrand made from two derivatives of linear shape functions is itself constant. A single midpoint therefore reproduces the stiffness exactly, despite failing for the consistent mass. If \(EA(x)=1+x^2\), the same midpoint now approximates its integral by 1.25, whereas the exact result is \(4/3\). The difference is \(1/12\) in the chosen units. A rule sufficient for one element contribution may thus be insufficient for another in the same analysis.
To select a quadrature order systematically, multiply out the shape functions or their derivatives, coefficient field and mapping Jacobian in the reference coordinate. For discontinuous coefficients, a single smooth polynomial degree may not exist on the entire element. Splitting at the interface, or integrating separate material subcells, then addresses the modelling geometry more directly than increasing the polynomial exactness of one unbroken-panel rule.
Retain both endpoints and derive the best three-point rule
Some instruments already provide readings at the ends of every panel, or adjacent elements need to communicate values at a shared boundary. If endpoints must be quadrature nodes, the unrestricted Gaussian degree \(2n-1\) is generally unavailable. To see the obstruction on \([-1,1]\) with \(n\) nodes including both ends, form the polynomial \((1-x^2)\prod_{\rm interior}(x-x_j)^2\). It vanishes at every evaluation point and is nonnegative throughout the interval. Its true integral is positive but every quadrature rule using just these values returns zero. Its degree is \(2n-2\), so exactness can extend at most through \(2n-3\).
For three symmetric nodes the interior point is zero. Symmetry forces equal endpoint weights \(a\), with central weight \(b\). Reproducing the constants and the square gives \(2a+b=2\) and \(2a=2/3\), so
Odd powers integrate to zero by symmetry, hence the rule is exact through degree three, attaining its constrained upper bound. Under affine mapping this is the three-node Gauss–Lobatto rule, also known as the single-panel Simpson rule. Its weights and node placement now follow directly from a measurement constraint and a moment calculation.
Contrast endpoint inclusion with free node placement
Consider the local mass entry on one dimensionless interval \([-1,1]\) for a quadratic middle-node shape function \(\phi(x)=1-x^2\) and uniform density. Its exact consistent mass contribution is
The endpoint-constrained three-node rule sees values \(0,1,0\), giving \(4/3\), an overestimate of \(4/15\), or 25 percent. The discrepancy arises solely from the quartic term. For a quadratic field, reproducing the field at all interpolation nodes does not imply correct integration of its square.
A three-point Gauss rule has free nodes at zero and \(\pm\sqrt{3/5}\), with weights \(8/9,5/9,5/9\). The outer samples have \(\phi^2=(1-3/5)^2=4/25\). Their total contribution is \(2(5/9)(4/25)=8/45\); adding \(8/9\) recovers \(16/15\). In a nodal element the endpoint-constrained rule makes off-diagonal mass entries vanish when basis functions are evaluated only at their own interpolation nodes. This diagonal mass approximation facilitates explicit updates even while changing the exact form.
Selecting either rule is therefore a physical and numerical modelling choice. A modal frequency depends on the ratio of stiffness energy to mass energy, so changing one mass entry may shift computed frequencies even if a static patch test passes. If the density varies across the element, include its degree or smoothness in the integrand before claiming exactness from polynomial degree counting. A discontinuity inside a panel defeats this counting argument until the integration interval is split.
As a check on assembly, sum all rows of the mass matrix. The shape functions form a partition of unity, so the total mass of a constant field is the integral of the density. The nodal diagonal rule reproduces this total for uniform density despite the incorrect middle diagonal entry just calculated. Testing the mass of a constant alone would therefore fail to expose the approximation affecting internal motion.
Does a high polynomial degree resolve a narrow peak?
Integrate \(1/(x^2+a^2)\) on \([-1,1]\). The exact answer is \(2\arctan(1/a)/a\). Use the ordinary Legendre nodes without centring a separate subinterval on the peak; vary only its half-width \(a\).

Read values from the plot
| Gauss–Legendre nodes | Peak half-width 0.12 | Peak half-width 0.35 | Peak half-width 0.7 |
|---|---|---|---|
| 1 | 114.7 | 9.2744 | 1.3386 |
| 3 | 39.347 | 1.742 | 0.090369 |
| 5 | 19.029 | 0.41492 | 0.0066724 |
| 8 | 6.0323 | 0.051839 | 0.00013401 |
| 10 | 3.9106 | 0.013187 | 9.8795e−6 |
Change parameters · Does a high polynomial degree resolve a narrow peak?
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.
Chapter 6 · Adaptive integration and error estimates
Construct a local error estimate from nested Simpson panels, allocate an absolute error budget and recognise signals that defeat sampling-based adaptivity.
From first principles
Estimate a missing integral from two mesh sizes
Suppose a quadrature approximation on a fixed interval has the asymptotic form \(Q_h=I+Ch^p+o(h^p)\), where \(p>0\) is known from the rule and smoothness assumptions. Evaluate the same rule after halving all panel widths. Its leading error is divided by \(2^p\), so eliminating \(C\) yields
The magnitude estimates the remaining fine-grid error. For composite Simpson quadrature \(p=4\) and the denominator is 15. An adaptive algorithm repeats this comparison on individual panels. Giving children absolute budgets that sum to their parent’s budget makes local bounds additive,
The first inequality is exact, while the estimated local errors require the leading-power model to hold. Two rules can agree accidentally on unresolved structure, which makes independent refinement or smoothness information valuable for difficult integrands.
Derivation and applications
Set a meaningful integration tolerance when contributions cancel
An adaptive integrator can refine its mesh until truncation error is small, yet the requested relative accuracy may be limited by uncertainty in the integrand. Consider an integrable real \(f\) on \([a,b]\) with pointwise error bounded by \(|\delta f(x)|\le\eta|f(x)|\). This can represent a numerical evaluation error or a relative tolerance on measured input values. The resulting data-induced error in the exact integral is bounded directly by
If arbitrary signs of perturbation are allowed, the bound is attained by taking \(\delta f=\eta|f|\). Let \(I_+\) and \(I_-\) be the respective positive magnitudes of the positive and negative contributions. For \(I\ne0\) the relative sensitivity to the data is therefore
It equals one for a one-sign integrand and can diverge as the net area tends to zero. If the algorithm has an independent absolute discretization error budget \(E_Q\), add the separate errors before deciding whether the requested tolerance is meaningful,
Splitting at known sign changes makes estimates of the separate contribution magnitudes easier to audit. It does not undo cancellation in the underlying quantity. Correlated data errors can yield a less severe budget when their correlation is independently known; a uniform multiplicative calibration error, for example, scales the net integral itself.
Worked example
Budget a nearly balanced energy flux
Heat-flow contributions over an interval are \(I_+=1001\,\mathrm J\), \(I_-=999\,\mathrm J\). The net is \(2\,\mathrm J\), and \(\kappa_I=1000\). With relative data uncertainty \(10^{-4}\), the data alone allow a \(0.20\,\mathrm J\) discrepancy, or ten percent of the net value. Reducing the quadrature budget from \(0.010\) to \(0.001\,\mathrm J\) cannot deliver one percent total accuracy.
Second application
Select an absolute budget from a reporting target
A second experiment has \(I_+=8.0\), \(I_-=3.0\) and \(\eta=0.002\). The data contribution is at most \(0.022\). Reporting net area 5.0 to one percent allows absolute error \(0.050\). A quadrature budget of \(0.028\) or smaller fits the remaining allowance. Two subinterval budgets of \(0.014\) each would satisfy the same total constraint.
Use two resolutions to estimate a missing integral
Suppose a composite rule on a smooth integrand has \(Q_h=I+Ch^p+O(h^{p+2})\). Halving the uniform spacing gives
Subtract the two approximations to eliminate \(I\). The fine-grid error satisfies
The sign of this estimate matters if correcting the numerical answer. Its magnitude supplies an error indicator. The relation assumes the same leading power operates on both grids and that the error exceeds the noise in the data.
For Simpson’s rule \(p=4\). On a parent interval compare one Simpson panel \(S\) with two half-panels whose sum is \(S_2\). The fine estimate of the local integral error is \(|S_2-S|/15\), and an extrapolated value is \(S_2+(S_2-S)/15\). The comparison needs only two new function evaluations because the endpoints and original midpoint are reused. If the indicator is too large, split the interval and apply the same test to each child separately.
Build a global tolerance from local decisions
Let the total absolute tolerance be \(\epsilon\). Begin with the whole interval assigned that budget. When a panel splits, a simple allocation gives half its budget to each child. By induction the sum of all final panel budgets equals the original tolerance. If each local actual error lies within its budget, the triangle inequality bounds the global error by \(\epsilon\). In practice the indicators estimate those actual errors, so this last statement is conditional. Around a discontinuity the fourth-order expansion can fail, and tiny intervals can run into evaluation noise or floating-point spacing.
For signed integrals with strong cancellation, relative error alone is hard to interpret. A large positive area and nearly equal negative area may give a tiny sum that changes sign under rounding. Use an absolute tolerance meaningful for the physical output, possibly combined with a relative term based on a stable scale. Reusing shared endpoint values helps both reproducibility and cost, especially when each evaluation invokes a constitutive model or a simulation.
Inspect one accepted panel and one failure
On \([0,1]\) use \(f(x)=x^4\). One Simpson panel gives \(S=0.20833333\), and two panels give \(S_2=0.20052083\). Their difference divided by 15 is \(-0.00052083\). The corrected result is 0.2, exactly the known integral up to the printed rounding. Here the fourth derivative is constant and there are no higher powers in the integrand, so cancellation removes the entire leading error. An estimated error of \(5.21\times10^{-4}\) would pass a local tolerance of \(10^{-3}\) while \(10^{-4}\) would trigger another split.
Now consider a narrow triangular pulse entirely between 0.10 and 0.11 of the interval, with height one. Its exact area is 0.005. The five points initially used by adaptive Simpson are \(0,0.25,0.5,0.75,1\). Every sampled ordinate is zero. The algorithm would accept zero with a zero indicator, even with a very small tolerance. This failure follows from lack of information, and it applies to any finite deterministic sample set when arbitrary narrow features are permitted. If event times or material interfaces are known, partition at them before sampling. If smoothness bounds are available, they supply an independent scale for an initial mesh. A small estimated local error should be interpreted together with those physical and mathematical assumptions.
Choose an independent comparison
A practical confirmation is to integrate the same signal using a different initial split and a different set of quadrature nodes. If a narrow pulse missed on one mesh is intersected on the other, their discrepancy reveals that the earlier indicator was misleading. Agreement between both estimates improves confidence but still cannot rule out an arbitrarily narrow feature absent from both sample sets.
When a physical bound \(|f'|\leq B\) is known, it supplies complementary information. Across an unsampled gap of width \(h\) whose endpoint values are both zero, a possible positive pulse is bounded by two straight ramps of slopes \(+B\) and \(-B\). Integrating the triangular envelope gives a maximum hidden area \(Bh^2/4\). A credible slope bound therefore turns a statement about unsampled behaviour into a quantitative reason to reduce the largest gap.
Build an independent certificate for an accepted panel
Adaptive extrapolation estimates error by comparing sampled values. A rigorous alternative is available when the model supplies a valid bound \(M\) on the fourth derivative throughout an interval. For a single Simpson panel of full width \(H\), the absolute error is bounded by \(M H^5/2880\). One derivation uses the cubic Hermite interpolant through both endpoint values and the midpoint value with its derivative at the midpoint. Its remainder is \(f^{(4)}(\xi)(x-a)(x-m)^2(x-b)/24\) for \(m=(a+b)/2\), assuming sufficient smoothness. The factor multiplying the derivative has one sign throughout the interval.
Integrating that polynomial factor in absolute value gives \(H^5/120\), and dividing by 24 gives the stated denominator 2880. Simpson quadrature integrates the cubic interpolant exactly and sees precisely the same three values as the original function. The midpoint derivative enters this argument as a mathematical device but never has to be measured. With independent derivative bounds on separate panels, summing their absolute bounds gives a global certificate without assuming that leading error terms cancel. Such bounds can be conservative, especially when worst allowed curvature occurs only over a tiny region.
A peak that agrees at every initial sample
On \([0,1]\) consider \(f(x)=x^2(1-x)^2\), with zero endpoints and midpoint value \(1/16\). Its single Simpson estimate is \(1/24\). The exact integral is \(1/3-1/2+1/5=1/30\), hence the overestimate is \(1/120\). The fourth derivative is exactly 24. Substituting \(M=24,H=1\) gives the same bound \(1/120\), attained in this case because the fourth derivative has constant sign and magnitude. Dividing into two equal Simpson panels lowers the total bound to \(2(1/2)^5/120=1/1920\).
A different candidate integrand makes the danger of relying on the sampled discrepancy explicit. Let \(g(x)=1-\cos(8\pi x)\). The original three samples and the two additional quarter-point samples are all zero. Both the coarse and refined Simpson estimates are therefore zero, so the usual difference indicator vanishes. Yet its exact integral on the unit interval is one. An independently known derivative bound \(M=(8\pi)^4\) gives a positive a priori certificate; the coarse computation cannot legitimately claim a small guaranteed error from those samples.
For equal panels the total fourth-derivative bound here is \(M/(2880 n^4)\) for \(n\) Simpson panels. To ensure an absolute error below 0.01 using only this information requires \(n>(M/28.8)^{1/4}\), about 10.85, so eleven panels suffice. The guarantee costs more evaluations than an indicator that happens to stop immediately, but it addresses a different question. Before using it for noisy measured data, check whether a fourth derivative is physically bounded at all and account for sampling error in addition to quadrature.
On the oscillatory example an offset sample at \(x=1/8\) gives value two, exposing the failure immediately. That single observation is powerful diagnostically, but its inclusion alone does not provide an accuracy bound for every other admissible integrand. The derivative certificate applies to the whole class with the stated derivative limit and therefore answers a stronger question.
Allocate a certified global Simpson budget
Suppose two smooth regions have lengths \(L_i\) and known bounds \(M_i\) on the fourth derivative. Give region \(i\) exactly \(n_i\) equal Simpson panels. Its contribution to the absolute error bound is \(M_iL_i^5/(2880n_i^4)\). For a fixed total panel count the best continuous allocation minimises the sum of these two expressions. Differentiating with a multiplier gives \(M_iL_i^5/n_i^5\) constant across regions, hence \(n_i\) proportional to \(L_i M_i^{1/5}\). The exponent is one fifth because each extra panel reduces the fourth-power global error at a rate proportional to the inverse fifth power of the local panel count.
For two half intervals with \(M_1=1,M_2=32\) and twelve panels in total, this gives four panels first and eight second. Cancelling their common factor \(L^5/2880\), the uniform six–six design has bound \(33/6^4\). The proposed four–eight design gives \(1/4^4+32/8^4=3/256\), about 46 percent of the uniform bound. Both designs use the same number of panels, integrate through the common interface, and rely on the same two derivative certificates. This does not guarantee that the actual integral error is reduced by the same factor, because the worst allowed derivatives need not occur everywhere. It quantifies the improved guarantee before sampling begins, entirely independently of a potentially aliased adaptive indicator.
Construct a false convergence test for adaptive quadrature
Integrate \(\sin^2(4\pi x)\) from zero to one using a trial Simpson panel and its two half-panels. All five evaluation points are multiples of 1/4. Predict the two estimates and the error inferred from their difference.

Read values from the plot
| Position in integration interval | True integrand | Interpolant from five trial samples |
|---|---|---|
| 0 | 0 | 0 |
| 0.25 | 1.4998e−32 | 0 |
| 0.5 | 5.999e−32 | 0 |
| 0.75 | 1.3498e−31 | 0 |
| 1 | 2.3996e−31 | 0 |
Change parameters · Construct a false convergence test for adaptive quadrature
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.
Problem sheet 3 · Accuracy with few evaluations
Derive mapped Gaussian weights, expose an underintegrated element and design a tolerance check for a sharply localised signal.
Map a rule and check its units
Use the two-node Gauss rule to integrate \(x^2\) over \([1,4]\). Give physical nodes and weights. Compare with the exact antiderivative, then explain what happens if the reference weights are used without the mapping factor.
Worked solution
The midpoint is 2.5 and half-length is 1.5, so nodes are \(2.5\pm1.5/\sqrt3\) and weights are both 1.5. The sum of squared nodal values is \(2[2.5^2+(1.5/\sqrt3)^2]=14\), giving integral 21. The antiderivative gives
Using weights equal to one would report 14. When \(x\) is measured in metres, the weights carry metres and the integral carries m³. Ignoring the Jacobian is a scale error as well as a dimensional inconsistency.
Try this calculation. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Measure mass of an alternating displacement
On \(0\leq x\leq1\), linearly interpolate nodal values \((1,-1)\). Compute the exact squared norm, the one-point midpoint approximation and the two-point Gauss result. Explain which field escapes the one-point sampling.
Worked solution
Linear interpolation gives \(u=1-2x\), so
The midpoint value is zero, giving zero numerical norm with one point. The two Gauss nodes are \(1/2\pm1/(2\sqrt3)\), where \(u=\mp1/\sqrt3\). Weights \(1/2\) give \(1/3\).
The field changes sign inside the element and its node lies exactly at the one-point sample. Treating zero discrete norm as proof of zero field would introduce a spurious unconstrained mode.
Try this calculation. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Interpret an adaptive estimate
For a smooth interval, one Simpson panel gives 1.2000 and two half-panels give 1.1850. Estimate the signed correction, the corrected integral and whether an assigned tolerance of 0.0005 is met. Separately, a narrow pulse is known to lie between two sample positions. How would you modify the initial partition?
Worked solution
The correction to the fine value is
The extrapolated estimate is 1.1840. The local error indicator 0.0010 exceeds the budget, so refine both halves and reuse the existing nodal evaluations.
For a pulse with known edges, introduce breakpoints at the edges and sample its interior. An indicator assembled from two rules that both miss the pulse can be zero even when the physical integral is finite.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Notebook practice · Three nodes sampling a Gaussian ensemble
Chapter 7 · Divided differences and derivative data
Build an interpolating polynomial one measurement at a time and incorporate a measured slope at a repeated node.
From first principles
Append a node without changing earlier interpolation values
Suppose \(p_{k-1}\) already interpolates \(f\) at \(k\) distinct nodes \(x_0,\ldots,x_{k-1}\). A new polynomial can preserve all these values by adding a multiple of a product which vanishes at every old node. The new data at \(x_k\) then determine the only free coefficient,
This coefficient is the divided difference \(f[x_0,\ldots,x_k]\). For two nodes it is the ordinary secant slope. The higher coefficients can also be obtained by subtracting divided differences for overlapping node lists and dividing by the total interval width,
Each level has one more inverse power of the input unit than the preceding one. When nodes coincide, these formulas require limits; for example the first divided difference tends to \(f'(x_i)\) when the function is differentiable.
Derivation and applications
Convert a second divided difference into a curvature estimate
Three unequally spaced readings carry information about how fast a signal’s slope changes. Let the times be \(x_-=x_0-a,\ x_0,\ x_+=x_0+b\), with \(a,b>0\). Divide each consecutive value difference by its own interval before subtracting the two slopes. The second divided difference is that slope change divided by the full interval \(a+b\). Twice this value is the exact second derivative of the interpolating quadratic,
To infer its error as an estimate of the true curvature at \(x_0\), expand the right and left secants about the central reading. Assuming four continuous derivatives locally, their leading terms are
Subtract and divide by half the full span. For \(h=\max(a,b)\) the result is
The leading error changes sign if the sampling geometry is reflected through \(x_0\). A symmetric panel cancels it and produces a second-order estimate; an arbitrary asymmetric panel with both spacings scaled together generally gives first-order accuracy at the middle node. This geometric error can matter even if every reading is exact.
Worked example
Detect curvature bias from asymmetric time stamps
Take \(f(t)=t^3\) and times \(-1,0,2\). The left secant is 1 and the right secant is 4. The formula gives \(D_2=2(4-1)/3=2\), whereas \(f''(0)=0\). The predicted error is \((2-1)6/3=2\), exactly since the function is cubic. For the same data the estimator measures the exact curvature at \(t=1/3\).
Second application
Propagate bounded noise into an acceleration measurement
In a different experiment the times are \(-0.10,0,+0.10\,\mathrm s\), with independent unknown position errors bounded in magnitude by \(0.001\,\mathrm m\). The second-derivative weights are \(100,-200,100\,\mathrm{s^{-2}}\). Thus the worst noise error is
Doubling the spacing quarters this noise bound while increasing smooth-signal truncation error, a practical trade-off even on a symmetric grid.
Start from this chapter. A quadratic has constant second divided difference. Use that coefficient to explain why the four- and eight-cell runs show a factor of four at midpoints.
OneSimulation laboratory · Measure what interpolation does to a heat integral
Keep the previous fit
A new measurement arrives after a polynomial has been fitted to \(x_0,\ldots,x_{k-1}\). To preserve those measurements, add a multiple of \(\omega_k(x)=\prod_{j=0}^{k-1}(x-x_j)\). At each old node the correction vanishes. At a new distinct node \(x_k\) its coefficient is fixed by \(c_k=(f(x_k)-p_{k-1}(x_k))/\omega_k(x_k)\). This gives a triangular construction. Once a coefficient has been determined it remains in every subsequent polynomial provided the original order is retained.
The coefficients can also be obtained using a table. Put \(f[x_i]=f(x_i)\) and subtract adjacent entries of the previous order before dividing by the distance between the two outer nodes. The subtraction cancels shared lower-order information. Algebraically the leading coefficient of the polynomial through \(x_i,\ldots,x_{i+k}\) is
This follows by combining the two lower-degree interpolants with factors \(x-x_i\) and \(x-x_{i+k}\). Their difference divided by the outer spacing agrees with every tabulated value and has the required leading coefficient.
Three temperatures and a test point
Suppose a temperature sensor reports 2, 5 and 17 degrees at 0, 1 and 3 hours. First divided differences are 3 and 6 degrees per hour. The second difference is \((6-3)/3=1\) degree per hour squared. Hence \(p(x)=2+3x+x(x-1)\). At hour 2 this gives 10 degrees; the original straight line would give 8. The correction shows how strongly the additional observation changes that prediction. Neither interpolant by itself certifies that the temperature really did reach its predicted value between readings.
Nested evaluation uses \(2+x[3+(x-1)]\) here. Each new layer adds one multiplication and one addition. Reordering the nodes changes the intermediate table, but uniqueness ensures the same final polynomial in exact arithmetic. Strongly unequal spacings can magnify noise in higher differences and make numerical results sensitive to the order.
Let two nodes coalesce
If a second node approaches the first, the corresponding difference quotient tends to \(f'(x_0)\) for differentiable \(f\). An independently available derivative therefore supplies the diagonal entry directly. For a value 1 and slope 2 at zero and a value 4 at one, the required quadratic is \(1+2x+cx^2\); matching the final value gives \(c=1\). Its prediction at one half is 2.25. Perturb the initial slope by 0.1 while keeping endpoints fixed. The correction becomes \(0.1x(1-x)\), attaining 0.025 at the midpoint. Endpoint agreement alone would miss that uncertainty.
Rescale before comparing coefficients
The coefficients have different units at successive orders. In the temperature example, expressing time in minutes divides the first divided differences by 60 and the second difference by \(60^2\). Their smaller printed magnitudes do not mean the curvature has become less significant. Evaluating the second term at the same physical instant multiplies by two correspondingly larger node differences and recovers exactly the original contribution. Scaling the node interval near unit size can make intermediate arithmetic more convenient; interpret a coefficient together with the product of distances it multiplies.
Differentiate a local interpolant on an uneven grid
For samples at \(x_0-a,x_0,x_0+b\), where \(a,b>0\), the derivative of their quadratic interpolant gives a three-point estimate of \(f'(x_0)\). Write it as \(w_- f(x_0-a)+w_0 f(x_0)+w_+f(x_0+b)\). Reproducing the derivatives of a constant, the centred coordinate and its square gives three equations: the weights must sum to zero, \(-a w_-+b w_+=1\), and \(a^2w_-+b^2w_+=0\). Solving yields
These are the same weights one obtains by differentiating Newton's divided-difference polynomial at the central node.
A Taylor expansion exposes the leading cubic contribution. On \(f(x)=(x-x_0)^3\), the estimate is \(-a^3w_-+b^3w_+=ab\), although the exact derivative is zero. Thus the leading smooth-data bias is \(ab f'''(x_0)/6\), with higher-order terms controlled by higher derivatives and panel geometry. Moving the nearest observation closer can reduce this deterministic bias while greatly increasing the magnitude of the weights. The calculation reveals the same conflict between localisation and noise that occurs when derivatives are inferred from independently measured values.
Estimate a heating rate from unsymmetrical sampling times
Choose \(x_0=0\), \(a=1\) minute and \(b=2\) minutes. The weights are \(-2/3,\ 1/2,\ 1/6\) per minute. Let the exact temperature over this short interval be \(T(t)=10+3t+t^3/10\) degrees. The sampled readings are
Applying the formula gives \(-4.6+5+2.8=3.2\) degrees per minute. The analytical derivative at zero is three. Its 0.2 bias equals \(ab T'''/6=(1)(2)(0.6)/6\), exactly because the temperature has no higher powers.
If each sample has independent standard deviation 0.12 degrees, the rate standard deviation is \(0.12\sqrt{4/9+1/4+1/36}=0.12\sqrt{26}/6\approx0.102\) degrees per minute. Halving both spacings reduces the cubic bias by four to 0.05, but doubles every derivative weight, increasing standard deviation to approximately 0.204. For the original grid, combining bias squared and variance gives mean squared error about 0.0504; for the refined grid it is about 0.0441. A further halving would make random error dominate still more strongly.
The weights sum to zero, so a truly common temperature offset cancels, while time-dependent drift need not. Also, using a symmetric central-difference formula on these asymmetric sample times would estimate a slope centred elsewhere and introduce a contribution from any quadratic term. Keeping the acquisition times in the coefficient equations is essential when observations are irregular because of missed triggers or variable sampling intervals.
A further check compares sampling the same temperatures with a fit that assumes the instrument clock is correct only to a tenth of a minute. At the central point the true local slope is three degrees per minute, so a timing error of 0.1 minute can by itself move a value by approximately 0.3 degrees. This is larger than the assumed independent temperature standard deviation. Errors in the sample locations would enter the divided differences through both numerator and denominator, and the simple fixed-time variance calculation would no longer describe the experiment.
Change parameters · Divided differences and derivative data
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
Approximating a resonance with a rational function · Function approximation and numerical integration
A smooth response on a measured interval can be governed by a nearby pole. Derive a low-order Padé fit, construct a barycentric rational approximant from samples and check whether a predicted pole survives independent data.
Chapter 8 · Uniform approximation and alternation
Certify a best uniform polynomial by finding alternating errors and compare its guarantee with interpolation at fixed nodes.
From first principles
Why alternating errors can certify a uniform approximation
To approximate \(f\) on a closed interval, measure the largest error in absolute value. A degree-\(n\) minimax polynomial is one for which no other polynomial of the same degree has a smaller largest error. Suppose a candidate \(p\) has absolute residual bounded by \(E>0\), and at \(n+2\) ordered points the residual attains alternating extrema,
If another polynomial \(q\) had error strictly below \(E\), the difference \(q-p\) would have to be positive at each positive residual extremum and negative at each negative one, or vice versa depending on the first sign. Continuity then forces
A nonzero polynomial of degree at most \(n\) cannot have that many roots. Thus the candidate is optimal once its global error bound and the alternating points are verified. Values sampled only at trial extrema do not certify that a still larger error is absent between them.
Derivation and applications
Remove the leading monomial with the least possible uniform error
Suppose a polynomial fit can represent every degree up to \(n-1\), but the signal contains one additional monomial \(x^n\). On \([-1,1]\) the residual \(x^n-p_{n-1}(x)\) is a monic polynomial of degree \(n\), regardless of the coefficients chosen for the fit. The Chebyshev polynomials provide a monic residual with particularly small uniform magnitude. Define \(T_n(\cos\theta)=\cos(n\theta)\). The cosine addition formula gives
By induction the coefficient of \(x^n\) is \(2^{n-1}\) for \(n\ge1\). Multiplying \(T_n\) by the reciprocal of that coefficient gives a monic polynomial bounded by \(2^{1-n}\) on the entire interval. Subtract it from the original target so that the highest powers cancel,
At the \(n+1\) points \(x_j=\cos(j\pi/n)\) the chosen residual equals \(2^{1-n}(-1)^j\). These alternating extrema certify optimality: a strictly better approximant would force its difference from \(p_{n-1}^*\) to change sign at least \(n\) times, exceeding the degree \(n-1\). For a leading term \(ax^n\) on a physical interval with midpoint \(m\) and half-width \(h\), the affine variable \(t=(x-m)/h\) shows that the optimal error scales as
Lower-degree terms can be carried into the approximant exactly. This result applies to uniform absolute error; changing to a mean-square criterion or weighting locations differently changes the optimization.
Worked example
Compress a cubic response to a quadratic model
For \(n=3\), \(T_3=4x^3-3x\), hence the best degree-at-most-two approximation of \(x^3\) on \([-1,1]\) is \(3x/4\). Its residual has magnitude \(1/4\) at \(-1,-1/2,1/2,1\), with alternating signs. The unused quadratic coefficient follows from the odd symmetry of the target and interval.
Second application
Scale the guarantee to a physical interval
Approximate \(2x^4+3x\) by a cubic on \([0,4]\). The half-width is 2, so the least possible uniform error is
An explicit optimum is \(2x^4+3x-4T_4((x-2)/2)\); its fourth-degree term cancels. Halving the interval width reduces the optimal error to \(4/16=0.25\) for the same polynomial target.
An error budget that applies everywhere
A calibration curve may have a specification requiring its largest absolute deviation anywhere in an interval to stay below a threshold. Assign a polynomial \(p\) of degree at most \(m\) and consider \(E(p)=\max_{a\leq x\leq b}|f(x)-p(x)|\) for a continuous target. Interpolating selected measurement locations fixes the polynomial there. It need not allocate the remaining error efficiently. Shifting an interpolant by a constant sometimes halves its largest deviation at once.
Suppose \(m+2\) ordered locations attain the same error magnitude with alternating signs. Any polynomial with strictly smaller maximum error must move up at each positive extreme and down at each negative extreme. Its difference from the candidate then has at least one zero between each consecutive pair. This requires \(m+1\) zeros in a polynomial of degree at most \(m\), a contradiction. Those extreme points thus certify optimality globally once the candidate's error is bounded over the entire interval.
Find the best line by hand
Approximate \(x^2\) on \([-1,1]\) by \(a+bx\). Averaging that line with its reflection gives the constant \(a\). For each \(x\), the averaged error is the mean of the errors at \(x\) and \(-x\), so the uniform norm cannot increase. For constants the target covers the whole range from zero to one. The midpoint \(a=1/2\) balances its two extreme distances. At \(-1,0,1\), the errors are \(+1/2,-1/2,+1/2\). These three points certify the optimum among all lines, including nonsymmetric ones.
The endpoint interpolant is the constant 1. Its error is zero at both ends and reaches magnitude 1 at zero. Lowering the line sacrifices exact agreement with the endpoints in exchange for a factor of two in the worst case. If the endpoint values encode compulsory boundary conditions, such a shift is inadmissible and the optimisation problem must include those constraints.
Exchange trial extrema
For an unknown target, guess \(m+2\) extreme locations and solve the linear system \(f(x_i)-p(x_i)=(-1)^iE\) for the coefficients and \(E\). Search the full interval, including its boundaries, for the largest deviation. When it exceeds the trial level, exchange a support point while retaining sign alternation and repeat. For smooth targets, the zeros of \(f'-p'\) supply candidate interior extrema. A coarse plotting grid alone cannot certify the resulting maximum.
For a constant approximation to \(e^x\) on \([0,1]\), monotonicity identifies the endpoints immediately. Equalising \(a-1=e-a\) gives \(a=(1+e)/2\) and error \((e-1)/2\), approximately 0.85914. Replacing the upper endpoint by a larger value raises both quantities. The constant optimum depends on the range, providing a simple independent check on an implementation of the exchange procedure.
A lower bound from three measurements
Suppose measurements at \(-1,0,1\) give the exact values \(1,0,1\) but the interior shape is otherwise unknown. Any line still has maximum error at least one half on those three measurements: averaging its two endpoint predictions recovers its value at zero, so it cannot be within less than one half of both endpoint targets and the central target. The lower bound survives with sparse data. The matching upper bound requires information between the measurements, supplied in the earlier example by the analytic formula \(x^2\).
Exploit symmetry to approximate a kink by a quadratic
The absolute-value function on \([-1,1]\) has a derivative jump at zero. To fit it uniformly with a quadratic \(p\), average \(p(x)\) with \(p(-x)\). The maximum error cannot increase because the target is even and the error of the average is bounded by the average of the two original absolute errors. The optimisation can therefore start with an even polynomial \(a+bx^2\) and examine only \(0\le x\le1\). Its signed error is
A plausible minimax candidate has equal negative errors at both ends of this half interval and a positive interior maximum.
Equal endpoint errors require \(-a=1-a-b\), hence \(b=1\). Differentiation then puts the positive maximum at \(x=1/2\), where the error is \(1/4-a\). Equalising its magnitude with the endpoint magnitude \(a\) gives \(a=1/8\). Directly completing the square gives \(e(x)=1/8-(x-1/2)^2\) on the half interval. Its entire range is \([-1/8,1/8]\), so this construction has established the upper error bound at every point, including locations between the supposed extrema.
Certify the optimum and compare a smoother error measure
On the original interval the errors at \(-1,-1/2,0,1/2,1\) are \(-1/8,+1/8,-1/8,+1/8,-1/8\). If any quadratic had a strictly smaller uniform error, its difference from the constructed polynomial would have to alternate sign at those five locations. Continuity would require at least four distinct real zeros. A nonzero quadratic cannot have four real zeros, so the proposed approximation is globally optimal even among polynomials with a linear term. The unusually long alternation is a consequence of symmetry and the central kink; four alternating points would already suffice for degree two.
For comparison, the quadratic interpolating the two ends and the central kink is \(x^2\). Its error on the positive half is \(x-x^2\), ranging from zero to \(1/4\). Shifting it upward by one eighth cuts the maximum error in half. Now suppose the instrument is used predominantly near the centre, where its true ideal value is zero. The minimax polynomial introduces a nonzero prediction of \(1/8\) there even though the original interpolant was exact. The preference for uniform accuracy amounts to a decision about the acceptable errors at those specific operating points.
A differentiability-based search that checks only stationary points can also fail in this problem. The target has a corner at zero, where its left and right derivatives differ. The error maximum in absolute value there is determined by the one-sided behaviour. For piecewise-smooth targets, include breakpoints and endpoints along with the roots of the error derivative on every smooth segment. Omitting a kink can produce an apparent equioscillation pattern with an incorrect reported bound.
For uniform approximation at a tolerance of one tenth, the optimum error of one eighth proves that no quadratic can meet the requirement on this interval. A failure by one fitted polynomial alone would not establish this. The alternation certificate tells an engineer when changing the polynomial class or splitting at the kink is mathematically necessary.
Change parameters · Explore the worked calculation
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 4 · Data and uniform error
Update measurements in Newton form and certify a uniform approximation by following the signs of its error.
Add a fourth observation
At times 0, 1 and 2 a displacement takes values 1, 2 and 5. Construct its Newton polynomial. Append a value of 13 at time 3 and evaluate the revised prediction at 1.5.
Worked solution
The first differences are 1 and 3; the second is 1. The quadratic is
At 3 its value is 10.
The new coefficient is
The correction at 1.5 is \(0.5(1.5)(0.5)(-0.5)=-0.1875\). The revised value is
All three original nodes annul the added term.
Explore the related calculation with adjustable inputs. Vary a slope or endpoint value and examine how an interpolant changes between observations. Map this exercise’s interval to the unit interval before comparing the basis functions.
Combine a slope with two values
Find a quadratic with \(p(1)=4\), \(p'(1)=-1\) and \(p(3)=6\). If the last measurement changes by 0.2, find the change of the midpoint prediction while preserving the first two conditions.
Worked solution
Write \(p=4-(x-1)+c(x-1)^2\). At 3 this gives \(2+4c=6\) and hence \(c=1\). The midpoint prediction at 2 is 4.
The revised curvature coefficient rises by \(0.2/4=0.05\), so \(p(2)\) rises by 0.05. The effect at the repeated node and its derivative both vanish, as the original conditions demand.
Explore the related calculation with adjustable inputs. Vary a slope or endpoint value and examine how an interpolant changes between observations. Map this exercise’s interval to the unit interval before comparing the basis functions.
Certify a line
Approximate \(x^2\) on \([0,2]\) by a line parallel to its endpoint interpolant. Choose the vertical shift minimising the uniform error. Show that allowing a different slope cannot improve the result.
Worked solution
The interpolant is \(2x\). Its error \(x^2-2x=(x-1)^2-1\) lies between \(-1\) and 0. Dropping the line by 0.5 centres the error range, giving \(p=2x-0.5\).
At 0, 1 and 2 the errors are \(+0.5,-0.5,+0.5\). Any strictly better line would differ from this one by a polynomial changing sign twice. A nonzero linear polynomial cannot have those two distinct roots. Thus 0.5 is globally optimal.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Chapter 9 · Fourier projection and sampled frequencies
Recover periodic modes by projection and identify signals which become indistinguishable on a uniform sample grid.
From first principles
Recover a Fourier coefficient by orthogonality
For a square-integrable signal of period \(2\pi\), represent its main oscillations by harmonics \(e^{ikx}\). To choose the best coefficients in the integrated squared-error sense, set each residual inner product with an included harmonic to zero. Integration of a complex exponential gives the orthogonality relation
Consequently projection onto mode \(m\) gives
On a uniform grid \(x_j=2\pi j/N\), replacing this integral by the sample mean defines the normalized discrete coefficient,
The finite geometric series now vanishes unless two frequency labels differ by a multiple of \(N\). Such labels have identical sampled values, so the sampled coefficients can combine several underlying continuous frequencies. A physical sampling rate and restrictions on the input bandwidth are needed to associate a discrete coefficient with a unique physical harmonic.
Open full-size diagram
Derivation and applications
Predict spectral leakage for a tone between Fourier bins
A frequency may lie well below the sampling limit and still distribute energy across many discrete Fourier bins. Consider \(N\) equally spaced samples of a single complex tone of unit amplitude with \(\nu\) cycles across the record. Using a rectangular measurement window, \(x_j=e^{2\pi i\nu j/N}\) for \(j=0,\ldots,N-1\). Under the normalization giving unit amplitude for a tone exactly on its bin, the coefficient in bin \(k\) is
Set \(\delta=\nu-k\). If \(\delta\) is not a multiple of \(N\), sum the geometric progression and factor a phase out of both numerator and denominator. This gives
At a bin-centred frequency the corresponding limiting coefficient is one and all other bins vanish. At a fractional bin the tails are a consequence of observing a finite record. The total squared spectral weight remains fixed by orthogonality of the discrete basis,
Amplitudes in selected bins can therefore be smaller without any loss of input energy. The formula assumes a complex tone. A real cosine contains two complex tones at opposite frequencies, whose coefficients must be added with phase before comparing amplitudes near overlapping lobes.
Worked example
Quantify a half-bin mismatch
Take \(N=8\) and \(\nu=2.5\) cycles. Bins 2 and 3 each have magnitude \(1/[8\sin(\pi/16)]=0.641\). Together they contain \(2(0.641)^2\simeq0.821\) of the tone’s spectral energy. The remaining fraction is distributed among the other six bins even though the input contains only a single frequency.
Second application
Distinguish grid spacing from intrinsic frequency content
A recorder sampling at \(800\,\mathrm{Hz}\) takes 80 samples of a \(125\,\mathrm{Hz}\) complex tone. Its bin spacing is \(10\,\mathrm{Hz}\), placing the tone halfway between bins 12 and 13; each magnitude is
Extending the actual record to 160 samples gives \(5\,\mathrm{Hz}\) spacing and exactly 25 cycles. The normalized magnitude in bin 25 becomes one when the tone remains coherent across the longer measurement.
Orthogonality on a period
For a square-integrable \(2\pi\)-periodic signal define \(\langle f,g\rangle=(2\pi)^{-1}\int_0^{2\pi} f(x)\overline{g(x)}\,dx\). The exponentials \(e^{ikx}\) are orthonormal for integer \(k\). Integrating their product gives one when the frequencies coincide and zero otherwise because a nonconstant exponential completes an integer number of cycles. Minimising the squared mean discrepancy over modes \(|k|\leq m\) therefore gives
The residual is orthogonal to every retained mode.
Orthogonality also splits energy. The squared norm of the original signal equals the sum of the retained squared coefficient magnitudes plus the remaining squared error. This identity gives the truncation error exactly for a finite trigonometric series. For a general square-integrable periodic signal the projections converge in the mean-square norm. That statement concerns an integral; a narrow region of large pointwise error can contribute little to it.
Background · Why does a noninteger cycle spread power over several bins?
Project \(e^{i\nu x}\) on the integer harmonic \(e^{ikx}\) over a single observed interval of length \(2\pi\). Integrating the exponential exactly gives
For an integer \(\nu\), the limit at \(k=\nu\) is one and every other bin receives zero. A tone with \(\nu=3.5\) cycles has equal coefficient magnitudes \(2/\pi\) at bins 3 and 4. A longer record at the same sampling rate narrows the physical frequency interval between bins. Applying a taper changes the leakage shape because it changes the projection window. Adding zeros after the existing record samples that same windowed spectrum more densely, without extending the observed duration.
A resolvable frequency and an invisible one
Take \(f(x)=2+\cos(2x)+0.4\sin(5x)\). Projecting onto frequencies through three retains the constant and cosine. The remaining mean-square error is \(0.4^2/2=0.08\), so its root mean square is about 0.28284. Now sample at \(x_j=2\pi j/8\). At those points \(5x_j\) differs from \(-3x_j\) by \(2\pi j\). Thus the data are equally compatible with \(2+\cos(2x)-0.4\sin(3x)\). A discrete fit through frequency three can have zero sample residual yet disagree between nodes.
At \(x=\pi/8\), the two sine contributions are \(0.4\sin(5\pi/8)\) and \(-0.4\sin(3\pi/8)\). Their difference is about 0.7391. This unsampled point exposes the false low-frequency reconstruction. More generally the finite sum of \(e^{2\pi i(k-l)j/N}\) vanishes unless \(k-l\) is divisible by \(N\). This geometric-series argument explains frequency equivalence on the grid and also supplies the discrete orthogonality behind a Fourier transform.
Factor the discrete Fourier transform into short transforms
The discrete Fourier transform (DFT) maps \(N\) equally spaced samples \(x_n\) to \(X_k=\sum_{n=0}^{N-1}x_n W_N^{kn}\), with \(W_N=e^{-2\pi i/N}\). In this convention the forward transform has no normalization. The discrete Fourier coefficients are \(X_k/N\). Computing every sum directly uses order \(N^2\) operations. There is redundant work because the sample weights are powers of the same root of unity.
For even \(N\), separate \(n=2j\) and \(n=2j+1\). Since \(W_N^2=W_{N/2}\), the two partial sums are the length-\(N/2\) transforms \(E_k,O_k\) of the even and odd samples. Increasing \(k\) by \(N/2\) leaves both short transforms unchanged and reverses the sign of \(W_N^k\). A single product therefore supplies two entries:
For the four samples \((1,2,3,4)\), the even subsequence \((1,3)\) gives \((4,-2)\), while the odd subsequence \((2,4)\) gives \((6,-2)\). The multipliers are 1 and \(-i\). Combining the two pairs produces \((10,-2+2i,-2,-2-2i)\) in frequency order. The zero-frequency term recovers the sum of the samples. Conjugate symmetry holds because the samples are real. The Nyquist entry is real as it must be.
For \(N=2^m\), repeat the split down to length one. Each of the \(m\) stages contains \(N/2\) paired combinations, often called butterflies. The work scales as \(N\log_2 N\). The FFT computes exactly the same mathematical transform as the direct formula, up to rounding. An aliased high frequency still occupies the same discrete bin. Padding an already sampled record can interpolate its displayed spectrum but cannot supply independent measurements at the missing times.
Practise on sheet 5 · Find the zeros in an eight-sample spectrum without eight long sums. Further reading · MIT · 2.161 Signal Processing, Continuous and Discrete · The Fast Fourier Transform · The radix-2 FFT with decimation in time.
Smoothness and endpoint matching
Integrating a Fourier coefficient by parts divides by its frequency. The boundary term vanishes for a smooth periodic continuation. Repeating the operation shows faster coefficient decay when successive derivatives also match at the endpoints and remain sufficiently regular. A mismatch when a finite record is periodically repeated creates a jump. Near a jump partial sums develop oscillations, and adding modes confines them to a narrower region while a peak overshoot persists.
Start a numerical study by refining the sample grid with a fixed retained bandwidth. Then hold that refined grid and enlarge the bandwidth. The first experiment probes whether the coefficient estimates are polluted by unresolved modes. The second probes how much physical detail a deliberately truncated representation omits. A single refinement that changes both quantities makes these explanations difficult to distinguish.
The special frequency at half the sample rate
With eight equally spaced samples the mode \(\cos(4x)\) gives \(1,-1,1,-1,\ldots\), whereas \(\sin(4x)\) gives zero at every point. A phase shift of a sinusoid at precisely this frequency therefore changes its observed amplitude and can hide the entire oscillation. This explains the special treatment of the highest coefficient in an even-length real Fourier transform. Ten samples over the same period distinguish both sine and cosine components at frequency four because their sample values are now linearly independent.
Average partial Fourier sums to obtain a positive kernel
Ordinary Fourier projection cuts sharply from a retained coefficient to a discarded one. Instead average the first \(m+1\) symmetric partial sums, counting the constant-only projection as the first. Mode \(k\) then appears in \(m+1-|k|\) of those sums for \(|k|\le m\). Its coefficient is multiplied by \(1-|k|/(m+1)\). This triangular weighting is called a Fejér mean. Its convolution kernel is the squared modulus of the finite geometric sum \(\sum_{j=0}^m e^{ijx}\), divided by \(m+1\). Expanding that squared modulus counts exactly the same number of pairs with each index difference \(k\).
The resulting kernel is nonnegative and has unit integral when measured with the normalised period measure \(dx/(2\pi)\). The reconstructed value is thus a weighted average of the true values. If a real continuous signal lies between zero and one everywhere, this averaged approximation remains in the same interval. For continuous periodic functions the averages converge uniformly: continuity makes nearby signal values uniformly close, while away from the origin the geometric-sum formula bounds the kernel by a constant divided by \(m+1\). Splitting the convolution into these two regions makes the approximation argument explicit.
Compare the reconstructed amplitudes at fixed bandwidth
Take \(f(x)=\cos x+2\cos(3x)\), retaining bandwidth through three. Ordinary projection reproduces this finite Fourier series exactly. Averaging the four partial sums of orders 0 through 3 retains the first cosine with weight \(3/4\) and the third with weight \(1/4\). The reconstruction is \(0.75\cos x+0.5\cos(3x)\). At zero it predicts 1.25 instead of three. Since the omitted amplitudes are 0.25 and 1.5, orthogonality gives squared mean error \((0.25^2+1.5^2)/2=1.15625\). The loss is substantial precisely because the real signal contains strong energy near the edge of the chosen band.
For a periodic piecewise-constant indicator, on the other hand, preservation of the interval between zero and one can be more important than full transmission of high modes. At an isolated jump separating two flat values, symmetry of the kernel assigns equal weight to sufficiently close points on either side of the jump. As the bandwidth grows, the averaged limit at a jump is the midpoint of its one-sided limits under these conditions. It cannot reproduce both sides at the mathematical point of discontinuity, regardless of the convention used to label that point in a data file.
These guarantees concern the continuous kernel and accurate coefficients. Aliased coefficients computed from an insufficient grid represent a different periodic function; applying triangular weights after such sampling cannot recover the missing distinctions between frequencies. Separate the choice of smoothing weights from the acquisition resolution when comparing a nonnegative reconstruction with actual measurements.
The smoothing window also supplies a direct frequency-response test. Feeding the averaging routine a unit cosine at frequency two with bandwidth three should return half its original amplitude. Feeding a constant should return the constant unchanged. Together these probes distinguish a correctly normalised triangular response from an accidental averaging operation that also attenuates the mean.
Make two different waves agree at every sample
Sample each continuous signal eight times per second at \(t=j/8\). At these instants the phases of the two components differ by \(2\pi j\). A discrete Fourier transform of those measurements cannot determine which continuous waveform produced them.

Read values from the plot
| Time (s) | Two cycles per second | Ten cycles per second |
|---|---|---|
| 0 | 0 | 0 |
| 0.25 | 1.2246e−16 | 6.1232e−16 |
| 0.5 | −2.4493e−16 | −1.2246e−15 |
| 0.75 | 3.6739e−16 | 5.3897e−15 |
| 1 | −4.8986e−16 | −2.4493e−15 |
Change parameters · Make two different waves agree at every sample
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
Integrating cosine interpolants on nested grids · Function approximation and numerical integration
Chebyshev points turn polynomial interpolation into a cosine series. Derive the exact moments of each basis polynomial, explain aliasing and find a case where two consecutive quadrature grids confidently agree on the wrong answer.
Chapter 10 · Weighted projections and Legendre polynomials
Derive a best mean-square polynomial and determine how a change of weight changes what that polynomial predicts.
From first principles
Project a signal under a specified measurement weight
Choose a nonnegative weight \(w(x)\) and define the squared error of a model \(p\) by integration of \(w|f-p|^2\) over the interval of interest. Assume the candidate basis functions have finite, positive weighted norms and are mutually orthogonal. To find the best coefficient for a basis function \(\phi_j\), vary that coefficient while holding the others fixed. The derivative of the squared error is
At the minimum this derivative vanishes. All cross terms involving other basis functions disappear by orthogonality, leaving
Consequently each coefficient can be computed independently. For unit weight on \([-1,1]\), the Legendre polynomials are one natural choice. If an experiment samples unevenly or certain regions matter more, the implied weight and hence the best fit can change even though the basis spans the same set of functions.
Derivation and applications
Quantify the return from adding one orthogonal basis function
Given a limited coefficient budget, one may want to know exactly how much an extra term reduces integrated squared error. Consider a real signal \(f\), a positive weight defining an inner product, and an existing least-squares projection \(p\) onto a finite-dimensional space. Its residual \(r=f-p\) is orthogonal to every included basis function. Suppose a proposed function \(\psi\) overlaps the original space. Remove its projection first,
If \(v=0\), the added function contains no new direction. Otherwise the expanded space splits into the original space and the direction \(v\). The new projection is \(p+av\); expansion and minimization give
The benefit of adding the term follows immediately,
This expression is unchanged if the candidate is multiplied by a nonzero constant. It also explains why a large raw correlation with a candidate function need not imply new explanatory power: part of that candidate can be represented already. The chosen weight must be used consistently in all projections. A continuous integral and a discrete sum over experimental samples may define different gains.
Worked example
Calculate the gain from adding curvature
With unit weight on \([-1,1]\), fit \(f=x^2\) first by a constant. The constant fit is \(1/3\). Adding \(\psi=x^2\) introduces \(v=x^2-1/3\), equal to the residual. The integrated reduction is
The expanded fit reproduces the signal exactly.
Second application
Compare two candidate corrections to a measured constant
Take three equally weighted readings \(f=(2,3,7)\). The constant projection gives 4 and residual \((-2,-1,3)\). Two proposed centered shapes are \(u=(-1,0,1)\) and \(v=(1,-2,1)\). Their gains are \(5^2/2=12.5\) and \(3^2/6=1.5\) respectively. The first leaves squared error \(14-12.5=1.5\). The other centered shape is orthogonal to the first, so adding both eliminates the residual.
Distance depends on the observation
A large error over a small part of an interval may be acceptable when an instrument averages over the interval. With a positive integrable weight \(w\), minimise \(J(p)=\int_a^b w(x)|f(x)-p(x)|^2\,dx\) over polynomials of degree at most \(m\). The first variation in an arbitrary allowed direction \(q\) gives \(\int w(f-p)q=0\). Conversely this orthogonality implies
This Pythagorean identity proves uniqueness and explains why a residual with large local extrema can still be optimal in the chosen metric.
In a monomial basis these conditions couple every coefficient to every other. Choose polynomials \(\phi_j\) orthogonal for the same weight instead. Then \(p=\sum c_j\phi_j\) with \(c_j=\int wf\phi_j/\int w\phi_j^2\). Increasing the degree preserves every coefficient already computed. Using quadrature to estimate these integrals introduces another approximation. A rule that samples too sparsely can make two distinct basis vectors look identical under the discrete inner product.
Construct a basis on a symmetric interval
For unit weight on \([-1,1]\), start with \(1,x,x^2\). Odd integrands integrate to zero, so the first two are orthogonal already. Subtract the projection of \(x^2\) onto the constant, namely \(1/3\), and retain \(x^2-1/3\). Scaling this polynomial to take value one at the right endpoint gives \(P_2=(3x^2-1)/2\), the second Legendre polynomial. Its squared integral is \(2/5\), obtained by integrating its expanded fourth-degree square.
Approximating \(x^2\) by a line retains just \(1/3\). Squaring the residual and integrating gives
The mean-square error is half that number and its square root is about 0.29814. The worst local error occurs at the endpoints and equals \(2/3\). The constant \(1/2\) has smaller uniform error but a larger squared integral of \(7/30\). The objective function explains the difference without appealing to how a fitted curve looks.
Move the weight toward one endpoint
On \([0,1]\) choose density \(w(x)=2x\), normalised to integrate to one. Fitting a constant to \(f(x)=x\) now gives its weighted mean \(2\int_0^1 x^2\,dx=2/3\). The weighted mean-square error is
Equal weighting would instead place the constant at \(1/2\). Selecting a weight thus amounts to specifying the region over which a loss should be economical. When interpreting coefficients state the interval, basis normalisation and weight together; otherwise two reported coefficients can be different descriptions of the same fitted polynomial.
A discrete inner product can give a different optimum
If only the endpoints of \([-1,1]\) are sampled with equal weight, then \(x^2\) takes value one at every observation and the best discrete constant is one. Adding the midpoint with the same weight changes it to \(2/3\). Simpson weights on those three samples instead give \((1+4\cdot0+1)/6=1/3\), the exact continuous coefficient, because that particular integral is quadratic. A mismatch between a discrete fit and a continuous projection can thus arise entirely from the observation design, even with error-free measurements.
Represent multiplication by the independent variable
Orthogonal polynomials supply a bridge from projection to quadrature. Choose an orthonormal family \(\phi_0,\phi_1,\ldots\) on an interval with positive weight \(w\). Multiplication of \(\phi_j\) by \(x\) raises its degree by one. Its inner product with \(\phi_i\) for \(i<j-1\) vanishes, because \(\langle x\phi_j,\phi_i\rangle=\langle\phi_j,x\phi_i\rangle\) and \(x\phi_i\) has degree below \(j\). Consequently \(x\phi_j\) is a linear combination of just \(\phi_{j-1},\phi_j,\phi_{j+1}\). Choosing positive leading coefficients makes the outer recurrence coefficients positive.
Truncating this multiplication map to the first \(n\) basis functions gives a symmetric tridiagonal matrix. At a root \(\xi\) of \(\phi_n\) the omitted last recurrence term vanishes. The column \((\phi_0(\xi),\ldots,\phi_{n-1}(\xi))^T\) is then an eigenvector of the truncated matrix with eigenvalue \(\xi\). Thus a polynomial root-finding task for Gaussian quadrature nodes becomes a symmetric eigenvalue problem. This correspondence uses the same positive weight throughout. If projection coefficients were assembled with a different effective inner product from the quadrature moments, the nodes would describe a different measure.
Derive two-point Gaussian quadrature from a small matrix
On \([-1,1]\) with unit weight, use \(\phi_0=1/\sqrt2\) and \(\phi_1=\sqrt{3/2}\,x\). Both diagonal entries \(\int x\phi_i^2dx\) vanish by oddness. The off-diagonal entry is
The truncated multiplication matrix has zeros on the diagonal and \(1/\sqrt3\) off it, so its eigenvalues are \(\pm1/\sqrt3\). The two normalised eigenvectors have first-coordinate magnitude \(1/\sqrt2\). Symmetry makes the quadrature weights equal and their sum must be the mass of the interval, two; hence the two weights are both one.
A further spectral check reconstructs low moments without an integration table. Write the matrix as \(J\). Since \(J^2=I/3\), the quadrature estimate of the second moment is \(2e_1^TJ^2e_1=2/3\), whereas odd moments through three vanish. The rule therefore integrates every cubic exactly by linearity. At degree four the same formula predicts \(2/9\), while the true fourth moment is \(2/5\). Multiplication by \(x\) repeatedly can produce a component outside the retained basis that returns later to affect the observed moment; truncation eventually loses that information.
For nonsymmetric weights the recurrence diagonal is usually nonzero and the quadrature nodes need no longer occur in opposite pairs. A practical diagnostic remains available: all weights must be positive and their sum must equal the integral of the constant. Passing these checks is necessary but does not certify the node positions. Testing further independently known moments can expose a normalisation or indexing error that the constant check alone would miss.
For instance adding the same spurious offset to both computed quadrature nodes leaves the weights positive and unchanged. The integral of the constant still passes exactly, while the first moment becomes twice that offset instead of zero. On an interval invariant under reflection, testing one odd and one even moment quickly distinguishes centring errors from errors in the spacing or overall weight normalisation.
Change parameters · Explore the worked calculation
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 5 · Spectral measures of error
Distinguish mean-square projections on continuous and sampled intervals and interpret the residual energy.
Recover the invisible frequency
A recorder samples \(\sin(7x)\) at \(x_j=2\pi j/10\). Identify its low-frequency alias. Give a point where the two functions disagree, and find the mean-square energy of their difference over a period.
Worked solution
Since 7 is congruent to −3 modulo 10, the sampled signal agrees with \(-\sin(3x)\). At \(x=\pi/10\) their difference is \(2\sin(3\pi/10)\approx1.618\).
On the continuous period the two sine modes are orthogonal. Each has mean square \(1/2\), so their difference has mean square 1. A vanishing discrepancy at every sample therefore coexists with an order-one continuous error.
Explore the related calculation with adjustable inputs. Inspect continuous waves that agree at all recorded samples; the frequency-counting argument remains necessary to establish a whole-band guarantee.
Which modes deserve space?
Let \(f(x)=1+0.6\sin x+0.8\cos(4x)\). Compute its mean square, the root-mean-square error after retaining frequencies at most one, and the best additional single real basis function among all higher-frequency sine and cosine modes.
Worked solution
Pairwise orthogonality gives
Omitting the fourth cosine leaves root-mean-square error \(\sqrt{0.32}\approx0.566\).
The only omitted nonzero coefficient multiplies \(\cos(4x)\). Adding this mode removes the entire remaining mean-square error. Choosing an intermediate frequency for its lower index would make no change for this specific signal.
Explore the related calculation with adjustable inputs. Inspect continuous waves that agree at all recorded samples; the frequency-counting argument remains necessary to establish a whole-band guarantee.
Project an odd function
Find the best linear mean-square approximation to \(x^3\) on \([-1,1]\) with unit weight. Compute its squared integrated error and compare the optimum slope with endpoint interpolation.
Worked solution
Symmetry forces zero constant. Orthogonality to \(x\) requires
Expanding the square gives
Endpoint interpolation gives slope 1. The least-squares line trades endpoint accuracy for lower integrated loss.
Explore the related calculation with adjustable inputs. Compare the reduction produced by two orthogonal correction directions. The continuous integral and the finite observation sum use the same projection identity but different inner products.
Find the zeros in an eight-sample spectrum without eight long sums
A sensor returns \((1,2,0,0,1,2,0,0)\) at eight equally spaced times. Before computing any transforms, predict which four Fourier bins vanish. Use a four-point transform to find the other bins and verify the discrete energy identity for the unnormalised DFT.
Worked solution
Pair sample \(n\) with \(n+4\). The second weight differs by \(e^{-i\pi k}=(-1)^k\), so all odd bins cancel. For even \(k=2j\) the two halves reinforce and give twice the four-point DFT of \((1,2,0,0)\). Its entries are \(3,1-2i,-1,1+2i\). Thus
The sample energy is
The frequency-domain squared magnitudes sum to \(36+20+4+20=80\). Dividing by eight gives 10. Both the zeros and the energy check depend on the adopted transform convention. Reversing the exponent sign conjugates these coefficients and leaves their squared magnitudes unchanged.
Explore the related calculation with adjustable inputs. Inspect continuous waves that agree at all recorded samples; the frequency-counting argument remains necessary to establish a whole-band guarantee.
Revisit chapter 9 · Factor the discrete Fourier transform into short transforms.
Chapter 11 · Quadrature near singularities and oscillations
Transform integrable endpoint singularities and use phase information to diagnose a misleading quadrature result.
From first principles
Remove an integrable endpoint singularity by substitution
An integrand can be unbounded and still have finite area. Consider \(f(x)=x^{-\alpha}g(x)\) on \([0,1]\), where \(g\) is continuous and bounded and \(0<\alpha<1\). The power law has a finite integral near zero since
Ordinary endpoint rules may still try to sample \(f(0)\), which is undefined. Substitute \(x=t^q\) and include the Jacobian \(dx=q t^{q-1}dt\). The transformed integral becomes
Taking \(q=1/(1-\alpha)\) removes the explicit power. For a square-root singularity the familiar substitution \(x=t^2\) gives a regular factor \(2g(t^2)\). Continuity of the transformed integrand makes endpoint evaluation meaningful, while the convergence order of a high-order rule still depends on how many transformed derivatives are bounded.
Derivation and applications
Subtract a known endpoint contribution before integrating the remainder
A substitution is one way to handle an integrable endpoint singularity. If an expansion of its smooth coefficient is known, a second route is to integrate a few singular terms analytically. Consider \(I=\int_0^1g(x)/\sqrt{x}\,dx\) with \(g\) twice continuously differentiable and \(|g''|\le M\). Taylor’s theorem about \(x=0\) separates the constant and slope from a remainder bounded by \(Mx^2/2\),
The first two contributions have finite known moments. The residual now vanishes at the problematic endpoint and can be sampled continuously there,
If only the short initial interval \([0,h]\) is targeted, the two analytic terms scale as \(\sqrt h\) and \(h^{3/2}\). Bounding the remaining contribution yields a direct local error certificate,
The two known coefficients have to use the same units and coordinate origin as \(h\). Numerically it can be advantageous to evaluate the residual through a stable expression or a local series, because subtracting its first two terms from a nearly equal value of \(g(x)\) can lose relative precision.
Worked example
Integrate a polynomial endpoint layer
For \(g(x)=1+3x+2x^2\) and \(h=0.04\), the two retained terms give
The remaining integral is \(2(2/5)h^{5/2}=0.000256\), giving total \(0.416256\). The error bound with \(M=4\) also equals \(0.000256\), attained because the curvature has constant sign and magnitude.
Second application
Choose an endpoint panel from a tolerance
A different coefficient has verified \(|g''|\le10\). To limit the omitted endpoint area to \(10^{-5}\), require \(2h^{5/2}\le10^{-5}\), or \(h\le(5\times10^{-6})^{2/5}=0.00758\). Choosing \(h=0.005\) gives a bound \(3.54\times10^{-6}\). The remaining regular part of the integral still needs its own quadrature budget.
When derivative bounds fail
The usual trapezoid error bound needs a bounded second derivative. The integral of \(x^{-1/2}\) from zero to one is finite, yet the integrand itself is undefined at the first endpoint. Calling a closed quadrature formula on its original samples is already impossible. Simply omitting that endpoint also omits part of a finite area, and its size scales as the square root of the omitted interval. A substitution can encode the known local behaviour exactly.
Set \(x=t^q\). A factor \(x^\alpha dx\) becomes \(qt^{q(\alpha+1)-1}\,dt\). For \(\alpha>-1\), choosing \(q=1/(\alpha+1)\) removes the leading power. Any additional factor \(g(t^q)\) still determines the transformed smoothness. For \(\alpha=-1/2\), \(q=2\) and \(g(x)=1+x\), the integral becomes
Composite Simpson quadrature on just two equal panels is exact on this quadratic. Assign the endpoint of the transformed expression by its limit to avoid evaluating zero times infinity.
A deceptively constant sample
Now consider \(\int_0^1\cos(16\pi x)\,dx\). The exact value is zero, because eight periods fit the interval. At the nine nodes of an eight-panel uniform trapezoid rule each value is one. The computed area is one, a full unit of error for an analytic function. A finer grid of sixteen panels samples alternating signs and returns zero. Repeating the first calculation on four panels also returns one. Agreement between the four- and eight-panel estimates therefore gives a false impression of convergence.
The aliasing follows from summing a geometric progression of sampled complex exponentials. When the phase step is an integer multiple of \(2\pi\), neighbouring samples coincide. Changing the offset slightly can expose the problem even before changing the number of nodes. A bound involving derivatives recognises the difficulty because the second derivative grows quadratically with the phase frequency.
Use cancellation as part of the method
When the oscillatory factor is known analytically, integrate it rather than forcing the grid to resolve every period. For a differentiable amplitude \(g\), integration by parts gives
This identity shows how smooth amplitudes can produce small integrals even when pointwise values are large. For \(g=x\) and \(\omega=\pi\) on \([0,1]\), the boundary term vanishes. The remaining sine integrates to \(2/\pi\), giving \(-2/\pi^2\). A quadrature scheme that approximates the slowly varying amplitude by lines and integrates each line against the phase reproduces this result exactly for this example. If the phase itself is uncertain, that modelling error must be assessed separately from quadrature error.
Test integrability before applying the change
For \(f(x)=1/x\) on \((0,1]\) the substitution \(x=t^q\) leaves \(q/t\), still nonintegrable for every positive exponent. A numerical rule excluding zero may nevertheless return an ordinary finite number. The integral from a cutoff \(\delta\) to one is \(-\log\delta\), so reducing the cutoff by a factor of ten adds \(\log10\approx2.3026\) every time. That persistent change signals a divergent problem definition. It calls for a physically justified finite cutoff or a different mathematical quantity before refining a quadrature rule.
Integrate the singular weight exactly on each panel
Sometimes a substitution changes an integrable singularity into a regular function but also complicates the geometry or an expensive supplied amplitude. An alternative is product integration. Suppose \(I=\int_0^1 x^{-1/2}g(x)\,dx\) where only the smooth amplitude \(g\) is sampled. Replace \(g\) by its piecewise linear interpolant while keeping the weight exactly inside each local integral. The contribution of an endpoint sample equals the integral of the corresponding linear basis function against the singular weight. None of these weights requires evaluating \(x^{-1/2}\) at zero.
On a single panel covering the unit interval the basis functions are \(1-x\) and \(x\). Their weights are \(2-2/3=4/3\) and \(2/3\), respectively. They are positive and sum to two, the exact integral of the singular factor. The rule reproduces constant and linear amplitudes exactly. If \(|g''|\le M\), the pointwise error satisfies
Multiplying by the positive weight and integrating gives absolute error at most \((M/2)(2/3-2/5)=2M/15\). This derivation tracks smoothness of the amplitude that is actually interpolated.
Compare a weighted panel with an ordinary endpoint sample
Let \(g(x)=1+x^2\). The analytically integrated value is \(2+2/5=2.4\). The weighted panel predicts
The excess is \(4/15\), exactly the bound for \(M=2\), because the interpolating line lies above this convex amplitude throughout the open interval. A direct unweighted trapezoid evaluation would have tried to sample an infinite value at the left endpoint. The finite weights here contain all information about the integrable divergence.
For a more refined calculation divide at \(x=1/4\). On the first panel, rescaling \(x=t/4\) multiplies the singular measure by \(1/2\), so the local weights become \(2/3\) and \(1/3\). On the second panel use the basis \((1-x)/(3/4)\), \((x-1/4)/(3/4)\). The weight of its left endpoint is
The remaining weight is \(4/9\), since that panel's total singular measure is one. Combining adjacent contributions gives global weights \(2/3,8/9,4/9\) at the three sampled amplitudes.
The estimate is now \(2/3+(8/9)(17/16)+(4/9)2=2.5\). Its positive error has fallen from \(4/15\) to 0.1. Subdivision concentrated near the singular endpoint is one design choice, while error here also depends on where the smooth amplitude bends. If the amplitude itself has a discontinuity, splitting at that physical interface is necessary before invoking the second-derivative bound on either side.
The positive weights also control bounded amplitude uncertainty. If each of the three amplitude evaluations is uncertain by at most 0.01, the worst possible additional integral error is
The bound is achieved by a shared positive offset of 0.01. Unlike the deterministic interpolation discrepancy, this worst-case observation error will remain 0.02 under any further positive-weight refinement that still integrates constant amplitudes exactly. A complaint about slow convergence near the endpoint could therefore reflect either amplitude resolution or the data error floor.
Repeated amplitude measurements can reduce independent sampling variance but cannot remove the effect of a shared calibration offset.
Change parameters · Explore the worked calculation
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.
Chapter 12 · Monte Carlo integration and stratification
Estimate an integral from random samples, attach a sampling uncertainty and derive the gain from stratification in a simple case.
From first principles
Derive a Monte Carlo estimate and its sampling error
Draw independent, uniformly distributed points \(X_i\) on \([a,b]\), and suppose \(f(X_i)\) has finite variance \(\sigma_f^2\). The expected value of one function sample is its integral divided by the interval length. This immediately gives an unbiased integral estimator,
For independent draws, the variance of a sum is the sum of the variances. Dividing by the square of the sample count gives
Replacing \(\sigma_f\) by the empirical sample standard deviation estimates the standard error. The \(1/\sqrt N\) decrease concerns repeated sampling; it is not a deterministic bound on one estimate. Quadrupling the number of evaluations halves that standard error. Dependence between samples, an infinite variance, or a biased point generator changes the reasoning and the interpretation of the reported uncertainty.
Derivation and applications
Predict when a reflected random sample reduces integration noise
Uniform draws on \([0,1]\) have the same distribution after reflection about \(1/2\). This permits antithetic sampling, in which each independent draw \(U\) is paired with \(1-U\). For a square-integrable integrand \(f\), define the per-pair estimate \(Z\) as the average of its two evaluations. Both terms have the desired integral as their expectation, so
Assume \(m\) independently generated pairs and finite single-sample variance \(\sigma^2>0\). The two members within a pair can be correlated. Let \(\rho\) be their correlation. Expanding the variance of their sum gives
For the same \(2m\) evaluations, independent sampling has variance \(\sigma^2/(2m)\); thus negative correlation helps. The source of any reduction can be seen by decomposing \(f\) about the midpoint into symmetric and antisymmetric pieces,
Pair averaging keeps the first and cancels the second exactly. The two pieces are orthogonal under uniform integration, so cancellation removes the antisymmetric contribution to variability. It also uses two evaluations for each independent pair. Standard errors should therefore be calculated across the pair averages.
Worked example
Calculate the gain for a quadratic integrand
For \(f(x)=x^2\),
The covariance with its reflected partner is \(\int_0^1x^2(1-x)^2dx-1/9=1/30-1/9=-7/90\), giving \(\rho=-7/8\). At a fixed evaluation budget the variance falls by a factor of eight and the standard error by \(\sqrt8\). Each pair integrates the linear part about the midpoint exactly.
Second application
Recognize when the second evaluation is redundant
For \(f(x)=(x-1/2)^2\), reflection gives the same function value. Here \(\rho=1\) and the paired method has twice the variance of independent sampling at equal cost. With 200 evaluations and single-value variance \(1/180\), the independent standard error is \(1/\sqrt{36000}=0.00527\); using 100 independent pairs gives
Turn area into an expectation
For an integrable \(f\) on \([a,b]\), let \(U\) be uniform on the interval. Then \(I=(b-a)\mathbb E[f(U)]\). Independent draws give an unbiased estimator by averaging their function values and multiplying by the length. With finite variance \(\sigma^2=\operatorname{Var}(f(U))\), independence eliminates cross-covariances and gives
The typical size of the sampling error decreases with the square root of the sample count. Multiplying the budget by four halves the standard error.
In a numerical run replace the unknown variance by the sample variance with denominator \(n-1\). For a sufficiently large sample with a suitable distribution, a normal approximation provides an approximate confidence interval. A particular interval need not contain the exact answer. Heavy tails, correlated draws or a nearly unsampled small peak can make the estimated uncertainty unreliable. Recording the random seed reproduces the same sequence of sample values; independent seeds are needed for independent replications.
Four draws and the uncertainty they reveal
For \(f(x)=x\) on \([0,1]\), four illustrative draws at 0.1, 0.2, 0.7 and 0.8 have mean 0.45. Their squared deviations sum to 0.37, yielding sample variance \(0.37/3\) and estimated standard error \(\sqrt{0.37/12}\approx0.176\). The exact integral is 0.5, so the observed error is 0.05. Because the uniform variance is exactly \(1/12\), the true standard deviation for repeated sets of four draws is \(\sqrt{1/48}\approx0.144\). These three numbers answer different questions about this one run and its possible replications.
Guarantee some coverage before sampling
Divide the interval into \(n\) equal strata and draw one independent point uniformly inside each. Sum each sample value times its stratum width. The estimator remains unbiased since each local expectation equals the mean over its stratum. For \(f(x)=x\) every local variance is \(1/(12n^2)\). Multiplying by the squared width and summing \(n\) independent contributions gives a total variance of \(1/(12n^3)\). For four samples the standard deviation drops to about 0.0361. The gain comes from fixing the amount of sampling effort in each region.
A single sample per stratum cannot estimate its own local variance. Independent repetitions of the complete stratified procedure or more samples per stratum permit empirical uncertainty estimates. In high dimension a full Cartesian partition requires rapidly growing numbers of cells. Simple Monte Carlo retains the same square-root rate under finite variance, but the variance constant and the cost of sampling can still depend strongly on dimension. Identify both the estimator and the method used to measure its uncertainty when reporting a numerical integral.
Use a known integral to reduce variability
For \(f(x)=x+x^2\), the integral of the first term is known to be one half. Sampling only \(x^2\) and adding one half leaves the expectation unchanged. The original sample variance per uniform draw is
The residual sample variance per draw is \(1/5-(1/3)^2=4/45\), less than one third as large. This control-variate construction uses a known mean and a correlation with the original integrand. An arbitrary replacement by a superficially similar function without restoring its known mean would bias the estimate.
Sample more often where the integrand is large
For a nonuniform positive probability density \(q\) on the integration region, the identity \(\int f(x)\,dx=\mathbb E_q[f(X)/q(X)]\) holds whenever the sampling distribution covers the integrand's support. Independent samples produce an unbiased estimate. Its variance per draw is \(\int f(x)^2/q(x)\,dx-I^2\), provided this integral is finite. A density concentrated near large contributions can reduce this variance even if generating a nonuniform draw costs little more than generating a uniform one. A density that is too small where the integrand is large can have the opposite effect.
Cauchy–Schwarz applied to \(\int |f|=\int (|f|/\sqrt q)\sqrt q\) gives
Equality requires \(q\) proportional to \(|f|\). For a nonnegative integrand that ideal density makes the sample weight constant and the variance zero. Constructing its normalising constant would generally require knowing the integral itself. The result is thus a design guide: choose a tractable density approximating the shape of the large contributions, with known normalisation and sufficiently broad coverage.
Restore finite variance for an integrable endpoint peak
Take \(f(x)=x^{-1/2}\) on \((0,1]\). The integral is two. Under uniform sampling each weight is finite almost surely and has that finite mean, but its second moment is
The familiar standard-error formula based on a finite variance and a square-root sampling rate is therefore unjustified, even if a modest run happens to avoid tiny \(x\) and reports a reassuringly small sample variance.
Choose \(q(x)=(3/4)x^{-1/4}\). Its cumulative distribution is \(x^{3/4}\), so one draws \(X=U^{4/3}\) for a uniform \(U\). The importance weight is
The second moment is \((4/3)\int_0^1 x^{-3/4}dx=16/3\), giving variance \(16/3-4=4/3\). For 300 independent draws the exact standard deviation of the mean is
This result quantifies an uncertainty that uniform sampling could not express through a finite variance.
For the ideal comparison \(q_\ast=x^{-1/2}/2\), the cumulative distribution is \(\sqrt x\); generating \(X=U^2\) gives \(W=2\) on every draw. Change the integrand to \(x^{-1/2}(1+x)\) while retaining this density and the weights become \(2(1+X)\), bounded between two and four. The method still controls the singular behaviour without needing exact knowledge of the new integral. For a sign-changing integrand, even sampling from \(|f|\) retains sign fluctuation and cannot eliminate cancellation between large positive and negative contributions.
To check the improved density numerically, record both the sample mean and the largest weight across independent replications. A computation that clips extremely small sampled values of \(X\) to avoid a large weight changes the target expectation. Under the proposed \(q\), the omitted integrand area from zero to a cutoff \(\delta\) is \(2\sqrt\delta\). Even a cutoff of \(10^{-4}\) removes 0.02 integral units, which is already thirty percent of the quoted standard error for 300 samples. Tail handling is therefore part of defining the estimator.
A stable implementation can generate the weight directly from the sampled uniform variable and check this omitted-area estimate.
Compute the expected benefit of stratifying a smooth integrand
Estimate \(\int_0^1 x\,dx\) by sampling function values. A uniform draw has variance 1/12; a draw restricted to a stratum of width \(1/N\) has variance \(1/(12N^2)\). Combine \(N\) independent equal-weight draws in each design.

Read values from the plot
| Number of independent uniforms | Independent uniform samples | One point per equal stratum |
|---|---|---|
| 2 | 0.20412 | 0.10206 |
| 8 | 0.10206 | 0.012758 |
| 32 | 0.051031 | 0.0015947 |
| 64 | 0.036084 | 0.00056382 |
| 256 | 0.018042 | 7.0477e−5 |
Change parameters · Compute the expected benefit of stratifying a smooth integrand
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
Spend random samples where they reduce uncertainty · Function approximation and numerical integration
A Monte Carlo estimate can be unbiased and still too noisy to be useful. Derive control variates, allocate a fixed budget across strata, and distinguish variance reduction from an underestimated standard error.
Problem sheet 6 · Choosing where to sample
Exploit endpoint structure, test aliasing and design a stratified random estimate with a known variance.
Remove a singular factor
Evaluate \(\int_0^1 x^{-2/3}(1+x)\,dx\) using \(x=t^q\). Select \(q\), derive the transformed integrand, and decide whether one Simpson panel pair gives the exact integral.
Worked solution
To neutralise the power require \(q(1-2/3)-1=0\), giving \(q=3\). Then \(x^{-2/3}dx=t^{-2}3t^2dt=3dt\) and the finite endpoint value is 3.
Integrating \(3(1+t^3)\) gives
Simpson is exact on cubics; its three samples are \(3,3.375,6\), and their weighted sum divided by six is 3.75.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Expose a false agreement
For \(f(x)=\cos(12\pi x)\) on \([0,1]\), find the trapezoid results with 3 and 6 panels. Test 12 panels and explain why the initial equal answers cannot justify a zero error estimate.
Worked solution
With three panels the phase advances \(4\pi\) at each sample; with six it advances \(2\pi\). Both return the constant sample average 1.
With twelve panels samples alternate between 1 and −1. The half-weight endpoints together count as one positive value, so all contributions cancel. The exact integral is zero. Correlated aliasing on the first two grids invalidates a smooth-error extrapolation.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Two strata with different variability
A response has variance 1 on the first half of \([0,1]\) and 4 on the other half. Estimate the integral from twelve independent evaluations. Compare the variances for allocations (6,6) and (4,8). Derive the continuous optimum under the same fixed budget.
Worked solution
Each stratum mean has variance \(\sigma_i^2/n_i\) and weight \(1/2\), so total variance is \((1/n_1+4/n_2)/4\). Equal allocation gives \(5/24\); (4,8) gives \(3/16\), slightly smaller.
Differentiating \(1/n_1+4/(12-n_1)\) gives \(-1/n_1^2+4/(12-n_1)^2\). Its zero requires
Positive second derivative yields the optimum (4,8), allocating in proportion to each stratum's standard deviation.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Choose a quadrature variable before choosing a rule
Estimate the integral of exp(−x)/√x from 0 to 1. A composite trapezoidal rule in x fails at its first endpoint. Remove the singularity by substitution, compute Simpson estimates using two and four panels in the new variable, and derive a practical error estimate. Explain why fitting a polynomial to the original endpoint would change the question.
Worked solution
Set x = t². The Jacobian 2t cancels 1/√x for t positive, and the integrand extends smoothly to g(0) = 2. The integral is now the integral of 2 exp(−t²) over [0,1]. The endpoint value is a limit implied by the model and the substitution.
With two equal panels Simpson gives [g(0)+4g(0.5)+g(1)]/6 ≈ 1.49436. With four panels the weights are 1,4,2,4,1 times 1/12, giving about 1.49371. If the leading error is proportional to h⁴, the estimated fine-grid error magnitude is |S₄−S₂|/15 ≈ 0.000043.
The exact benchmark √π erf(1) ≈ 1.4936483 shows that the fine-grid estimate is already close; the asymptotic estimate is approximate on these coarse grids. Replacing the infinite original endpoint by a fitted finite number amounts to imposing an arbitrary sampling model. The substitution preserves the exact integral and also explains why a higher-order rule now has the smoothness it needs.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Chapter 13 · Evaluating an interpolant without rebuilding its polynomial
Derive a quotient from the Lagrange basis, evaluate the removable singularity at a data point and separate rounding error from sensitivity to the data.
One product shared by all the basis functions
Let distinct nodes \(x_0,\ldots,x_n\) carry data \(y_j\). The cardinal function \(\ell_j(x)\) is one at node \(j\) and zero at the other nodes. Its product formula is expensive if every evaluation repeats the same differences. Set \(w_j=1/\prod_{k\ne j}(x_j-x_k)\) and \(P(x)=\prod_k(x-x_k)\). Away from all nodes,
The polynomial interpolating constant data equal to one is one everywhere. Dividing the interpolating polynomial by this partition of unity cancels \(P(x)\) to give
At a node the written quotient divides infinities. Multiply numerator and denominator by \(x-x_j\) and take the limit to recover \(y_j\) exactly. An implementation should return the stored value when the evaluation coordinate equals a node. Multiplying every weight by the same nonzero factor leaves the quotient invariant, a useful freedom when storing weights.
Background · Barycentric weight
Only relative weights enter the rational expression for the interpolating polynomial. At a node return the recorded value directly.
Worked interpolation and data sensitivity
Take the nodes \(-1,0,1\). Their weights are proportional to \(1,-2,1\). With data \(1,0,1\) at \(x=0.5\), the numerator is \(2/3-2=-4/3\) and the denominator is
Hence \(p(0.5)=1/4\), as the polynomial \(x^2\) requires.
Change the middle datum from 0 to 0.01. Its cardinal function is \(1-x^2\), so the prediction at 0.5 rises by 0.0075. For arbitrary data perturbations bounded by \(\delta\), the triangle inequality gives
Large values of this sum signal a sensitivity of the interpolation problem. Evaluating the same polynomial by a smarter formula cannot remove this source of error.
Put more sensors near the endpoints
Approximate \(f(x)=1/(1+25x^2)\) on \([-1,1]\). Both curves use the same number of exact samples and the same barycentric algorithm. One uses equally spaced nodes and the other uses projections of equally spaced angles on a semicircle. Check the interior before inspecting the ends.
Tutorial on what the formula guarantees
Why do three weights with alternating signs produce an answer between zero and one in the first calculation? Must it always lie between the smallest and largest data?
Worked solution
The example reconstructs \(x^2\), which stays within that range on this interval. General cardinal functions may be negative. Unlike a convex combination, their weighted sum can overshoot the sampled range.
For the three nodes above, perturb only the datum at \(-1\) by 0.04. What is the change at \(x=0.5\)?
Worked solution
The left cardinal polynomial is \(x(x-1)/2\), equal to \(-1/8\) at \(0.5\). The change is \(-0.005\), with the opposite sign to the perturbation.
Read the university treatment
Compare the construction of weights with the theorem on the barycentric form. Reuse the same nodes to reproduce the data-perturbation calculation. Driscoll and Braun · Barycentric interpolation
Chapter 14 · When a trapezoidal sum counts the wrong frequency perfectly
Use a finite geometric series to explain why a very accurate periodic quadrature rule can completely miss an oscillation.
Summing one Fourier mode
A smooth closed curve parameterised by angle provides a natural periodic integral. On \(N\) equally spaced points \(\theta_j=2\pi j/N\), write the trapezoidal estimate of a mean as \(T_N=N^{-1}\sum_{j=0}^{N-1}f(\theta_j)\). The endpoint \(2\pi\) equals zero angle and is counted only once. For \(f=e^{ik\theta}\), put \(q=e^{2\pi i k/N}\). If \(q\ne1\) then
If \(q=1\) all \(N\) samples equal one.
For a Fourier series whose absolute convergence permits termwise summation, this gives
The continuous mean sees only the constant mode. The grid silently adds every integer multiple of its sample count to that mode. Fast decay of smooth Fourier coefficients usually makes this error small. A single deliberately aligned harmonic can defeat the rule.
Background · Fourier alias
On n equally spaced periodic samples two distinct continuum frequencies can yield precisely the same observations. Interpolation cannot disambiguate them without more information.
Two rings of sensors
A ring carries the temperature \(20+3\cos(8\theta)\) °C. Eight sensors at zero angular offset all read 23 °C. The true mean is 20 °C. Nine equally spaced sensors give the exact mean for this harmonic. Moving the eight sensors through an offset \(\phi\) changes their mean to \(20+3\cos(8\phi)\) while the ring is unchanged.
A different signal \(2+\cos(3\theta)+0.2\cos(10\theta)\) on five sensors gives 2.2 because the tenth harmonic aliases to zero frequency. Increasing the number to ten gives the same wrong answer. Independent node offsets or a noncommensurate sample count can challenge an apparently converged result.
Move the sampling ring
The curve gives the mean reconstructed from rotated sensors over one revolution. Change the number of sensors and the physical harmonic separately. Predict the counts that will make the measurement depend on the angular offset.
Tutorial on resolution
A discrete test gives the exact mean of \(\cos(7\theta)\) on eight equally spaced nodes. Can eight samples reconstruct that frequency uniquely?
Worked solution
Its mean vanishes, but samples of \(\cos(7\theta)\) coincide with those of \(\cos(\theta)\) on this grid. Accurate integration of the mean does not imply unique reconstruction.
Average two \(N\)-point rules offset by \(\pi/N\). Which aliases survive?
Worked solution
Together the rings form a \(2N\)-point uniform grid. Terms at odd multiples of \(N\) change sign between grids and cancel. Terms at even multiples survive.
Study the full derivation
Integrating cosine interpolants on nested grids · Function approximation and numerical integration
Chebyshev points turn polynomial interpolation into a cosine series. Derive the exact moments of each basis polynomial, explain aliasing and find a case where two consecutive quadrature grids confidently agree on the wrong answer.
Chapter 15 · Deriving Romberg integration and recognising a broken error model
Build an extrapolation table from nested trapezoidal sums and explain when cancelling a presumed leading error makes a poor estimate look precise.
Cancelling a nuisance coefficient
Suppose a smooth integrand gives
Halving the mesh gives
Multiply the second formula by four, subtract the first and divide by three. The unknown \(a\) disappears without being estimated explicitly. The new leading error is \(-bh^4/4\).
At level \(j\) a smooth even-power expansion starts with a power \(h^{2j}\) to be removed from the preceding column. The same two-row elimination yields
Each refinement reuses all previous function values. Add only the midpoints of old panels, because every old endpoint becomes an even-indexed fine node. This is especially attractive when obtaining a sample means running an expensive smooth simulation.
Background · Richardson extrapolation
This cancels an assumed leading error proportional to h to power p. Several refinements can test whether that asymptotic regime is present.
Check the arithmetic twice
For \(\int_0^1 x^4\,dx=1/5\), the first three trapezoidal estimates are 0.5, 0.28125 and 0.220703125. The first extrapolation column contains 0.2083333 and 0.20052083. Combining them with coefficient 15 gives 0.2. This is an exact polynomial check on indexing and column orientation.
For \(\int_0^1\sqrt{x}\,dx=2/3\), the first two trapezoidal values are 0.5 and approximately 0.603553. Their extrapolate is about 0.63807. The derivative is singular at zero. The endpoint panel alone has an error proportional to \(h^{3/2}\), the same scale that dominates the global error. A factor of four cannot cancel it.
Change the regularity at the endpoint
Integrate \(x^p\) on the unit interval. Read absolute error for the raw trapezoidal estimates and their first extrapolation. The ordinate is the base-ten logarithm, with roundoff-level results displayed at the stated floor. Compare a smooth integer exponent and a fractional one.
Tutorial on interpreting a convergence table
Given three successive estimates with differences 0.008 and 0.002, what observed order do they suggest on uniform bisection?
Worked solution
A factor of four between signed differences is consistent with \(2^p=4\), hence order two. A further refinement tests whether this is an asymptotic regime.
Remove the square-root difficulty by a change of variable. What estimate becomes exact after one extrapolation?
Worked solution
Set \(x=t^2\), \(dx=2t\,dt\). The integral becomes \(\int_0^1 2t^2\,dt\). The raw trapezoidal error for a quadratic has only an \(h^2\) term, so first-column Richardson extrapolation is exact in exact arithmetic.
Read the university treatment
Work through their extrapolation example, then determine the observed order before extrapolating the square-root data in this chapter. Driscoll and Braun · Numerical integration
Chapter 16 · Summing a Chebyshev series by working backwards
Derive a stable evaluation scheme directly from a three-term polynomial identity and diagnose the failure that occurs when a fitted law is used outside its calibrated interval.
From cosines to a polynomial recurrence
Set \(x=\cos\theta\) and \(T_k(x)=\cos(k\theta)\). The angle-addition formula gives
with \(T_0=1,T_1=x\). Consider \(p=\sum_{k=0}^n c_k T_k\) with the constant coefficient included in full. We could generate all the polynomials forward. Clenshaw evaluation instead gathers their weighted coefficients from the high end, without converting to monomials.
Set \(b_{n+1}=b_{n+2}=0\) and \(b_k=c_k+2xb_{k+1}-b_{k+2}\) for \(k=n,\ldots,1\). Substitute \(c_k=b_k-2xb_{k+1}+b_{k+2}\) into the original sum. Every interior \(b_j\) multiplies \(T_j-2xT_{j-1}+T_{j-2}=0\). Only two boundary terms survive:
The derivation also identifies a common convention error. If the source defines its zeroth coefficient with a half-weight then it must be halved once before using this formula.
Two useful arithmetic checks
For coefficients \((1,2,3)\) at \(x=0.5\), \(b_2=3\), \(b_1=2+2(0.5)3=5\). The answer is
Independently \(T_2(0.5)=-0.5\), giving \(1+1-1.5=0.5\).
On the calibration interval each \(|T_k|\le1\), so an isolated coefficient error of 0.001 changes the value by at most 0.001. At \(x=1.2\), \(T_{10}(1.2)=\cosh(10\operatorname{arcosh}(1.2))\) is around 252. The same tiny coefficient error now changes a prediction by roughly a quarter of a unit. Accurate summation does not make extrapolation reliable.
Follow one uncertain coefficient
A simple calibration \(1+0.4x\) has an uncertain extra coefficient at a selectable order. Find the extreme differences inside the interval, then inspect the growth just beyond the right endpoint. The calculation uses the backward recurrence at every position.
Tutorial on mapping a laboratory interval
A calibration covers \(10\le T\le50\) °C. Which coordinate should enter the recurrence and what does \(T=54\) correspond to?
Worked solution
Centre at 30 and divide by the half-width 20, so \(x=(T-30)/20\). At 54 °C this gives 1.2, already outside the bounded Chebyshev interval.
Give a computable uniform error bound if three stored coefficients have errors no larger than 0.002 each.
Worked solution
For \(|x|\le1\), the triangle inequality and \(|T_k|\le1\) give 0.006. Exact values may cancel at some positions; this bound does not rely on such cancellation.
Read the university treatment
Compare coefficient decay inside the approximation interval with sensitivity to extrapolation beyond it. Lloyd N. Trefethen · Approximation Theory and Approximation Practice
Study the full derivation
Integrating cosine interpolants on nested grids · Function approximation and numerical integration
Chebyshev points turn polynomial interpolation into a cosine series. Derive the exact moments of each basis polynomial, explain aliasing and find a case where two consecutive quadrature grids confidently agree on the wrong answer.
Chapter 17 · Where should a random quadrature spend its samples?
Derive the weight that corrects a nonuniform sampling density and see why an unbiased quadrature can nevertheless have infinite variance.
Change the experiment while preserving its mean
For \(I=\int_0^1 f(x)\,dx\), choose a probability density \(p(x)>0\) wherever \(f\ne0\). If \(X\) is drawn from \(p\), then averaging \(W=f(X)/p(X)\) gives
With independent draws and finite second moment, the estimator variance is \([\int f^2/p-I^2]/N\). Merely changing the point distribution without changing the weight would compute a different integral.
For nonnegative \(f\), Cauchy–Schwarz gives
Equality holds if \(p\) is proportional to \(f\). The ideal distribution would give identical weights, although constructing its exact normaliser frequently requires already knowing the answer. It remains a guide to choosing an approximate density.
Background · Monte Carlo standard error
Independent samples with finite variance give this ideal error scale. Importance weights and correlations can substantially alter the variance of the actual estimator.
A finite expectation with an infinite error bar
For \(f(x)=x^{-1/2}\) the integral is 2. Uniform sampling produces weights \(X^{-1/2}\) whose second moment is
The estimate has the right expected value, but its usual finite-variance standard error has no foundation.
Take \(p_a(x)=(a+1)x^a\) with \(a>-1\). An inverse-CDF draw is \(X=U^{1/(a+1)}\) for a uniform \(U\). For \(f=x^b\), the second moment is \(1/[(a+1)(2b-a+1)]\) when \(2b-a>-1\). At \(b=a=-1/2\), \(X=U^2\) and every weight equals exactly two. At \(b=-1/2,a=-1/4\), the second moment is
The variance is 1.3333 and 100 independent draws have standard deviation about 0.1155.
Compare sampling plans on the same draws
Use the same fixed pseudo-random uniform sequence for the two plans so changes reflect the transformation. Sweep the proposal exponent through the finite-variance boundary and inspect the running mean. One finite trajectory can look benign even when the theoretical second moment diverges.
Tutorial on signs and diagnostics
If \(f\) changes sign, can sampling proportional to \(|f|\) remove every fluctuation?
Worked solution
Then the weight is a constant magnitude multiplied by the sign of \(f\). Its variance vanishes only if that sign is constant almost everywhere. Cancellation between positive and negative contributions can still make relative accuracy poor.
A proposal has zero density on a short interval where \(f\) is nonzero. Does increasing the number of samples repair the estimate?
Worked solution
No sample can reach that interval, so the corresponding integral contribution is absent. This is a bias from missing support; the derivation of \(E[W]=I\) fails there.
Study the full derivation
Spend random samples where they reduce uncertainty · Function approximation and numerical integration
A Monte Carlo estimate can be unbiased and still too noisy to be useful. Derive control variates, allocate a fixed budget across strata, and distinguish variance reduction from an underestimated standard error.
Chapter 18 · Integrating an infinite endpoint with a finite table of samples
A density rises without bound near the edge of a specimen, yet the total inferred amount can be finite. Choose nodes that measure the edge contribution accurately. Derive the tanh–sinh transformation, split two different quadrature errors and detect when refining a grid can no longer answer the physical question.
Determine whether a finite measurement exists
Let \(x\) be the distance from the edge divided by the specimen width. Take the idealised density \(f(x)=x^{-\alpha}\) on the open interval between zero and one. The exponent is a known input in this experiment. Start with \(0<\alpha<1\). If the instrument samples exactly at zero, its readout would be undefined in this model. That does not make the integrated signal infinite. The contribution of the first \(\varepsilon\) of the interval is found by integrating from a positive lower bound and taking that bound to zero.
This sets the physical scale of the numerical task. With \(\alpha=1/2\), the first one ten-thousandth of the spatial window contributes one per cent of the complete signal. For \(\alpha=0.9\), the same strip contributes almost forty per cent. An instrument with finite edge resolution may require a separate sub-resolution material model. In the numerical exercise the stated power law is exact down to arbitrarily small distance. That assumption permits an independent reference answer and lets us attribute a mismatch to the quadrature rather than to unseen edge physics.
A uniform midpoint rule avoids the forbidden endpoint, using \(h\sum_{j=0}^{N-1}f((j+1/2)h)\) with \(h=1/N\). The exact contribution of the first cell is \(h^{1-\alpha}/(1-\alpha)\). Its midpoint approximation is \(2^\alpha h^{1-\alpha}\). The leading error already visible in this cell decays slowly when the exponent is close to one. Since the density is convex, every midpoint panel underestimates its integral. The errors do not cancel the missing first-cell contribution. The usual smooth-function bound in terms of a uniform second derivative cannot be applied here.
Build a transformation that resolves both ends
Map a real parameter \(t\) onto the physical interval. A convenient first choice is a logistic map, which approaches either endpoint exponentially in the parameter. To concentrate the nodes more aggressively near the endpoints, first replace that parameter by \(\pi\sinh t\). Written using a hyperbolic tangent, the resulting map is the usual tanh–sinh transformation. Its derivative becomes small at precisely those points where the original density becomes large.
Apply the change of variables before choosing any quadrature rule. The new integrand is \(g(t)=\pi\cosh(t)x(t)^{1-\alpha}[1-x(t)]\), integrated along the entire real line. To inspect its left tail take \(t=-u\) with \(u\) large. Then \(\sinh u\) and \(\cosh u\) both grow approximately as \(e^u/2\), while \(x(-u)\) behaves as \(\exp[-(\pi/2)e^u]\). Their product decays like a factor proportional to \(e^u\) multiplied by \(\exp[-(1-\alpha)(\pi/2)e^u]\). The second exponential dominates eventually. As \(\alpha\) approaches one its coefficient shrinks and the relevant left tail extends farther out.
At the right end \(x(t)\) approaches one and the factor \(1-x(t)\) supplies the rapid decay. A symmetric truncation in \(t\) therefore covers two generally unequal tail contributions. On a real density that is singular at both ends, repeat the asymptotic argument separately for each endpoint. For a strong interior peak the present transformation has no reason to concentrate near the peak. Splitting the interval at a known interior singularity would give each transformed subproblem a meaningful endpoint.
Distinguish tail loss from the panel approximation
Choose a finite half-window \(T\), then a step \(h_t\) such that a whole number of panels fits on either side of zero. The notebook applies the composite trapezoid with half weights on both boundary nodes of \([-T,T]\). This calculation leaves out the two infinite tails even if the finite interval is integrated perfectly. There is a second error from replacing the finite integral by sampled trapezoids. At fixed window the panel errors can become tiny while an appreciable area is still missing.
In the power-law test the omitted tails can themselves be integrated explicitly. Write \(a=x(-T)\) and \(b=x(T)\). Their sum is \([a^{1-\alpha}+1-b^{1-\alpha}]/(1-\alpha)\). With \(\alpha=0.65,T=3,h_t=0.25\), there are 25 evaluations and the notebook gives about 2.85707045 against the reference 2.85714286. The omitted tail is approximately \(4.70\,10^{-5}\), while the total difference is about \(7.24\,10^{-5}\). The gap between these values belongs to resolution inside the chosen window. Recalculating at smaller \(h_t\) without increasing \(T\) tests only the latter.
Open full-size diagramCompute the weighted integrand before rounding the endpoints
If \(x\) is stored as exactly one, the expression \(1-x\) loses a small positive number. If \(x\) underflows to zero, multiplying \(f(x)=\infty\) by a derivative rounded to zero causes another failure. Both effects are artefacts of evaluation order. Here the product \(f(x(t))x'(t)\) has a simple algebraic form that is finite everywhere at finite \(t\). Working in logarithms keeps the two endpoint distances separately.
Put \(s=\pi\sinh(t)\). A stable evaluation of \(\log x\) is \(-\log(1+e^{-s})\), and that of \(\log(1-x)\) is \(-\log(1+e^s)\). The notebook calls NumPy's log-add-exp operation on zero and the respective exponent to avoid directly forming a very large exponential. The log of the complete integrand is now the sum of \(\log\pi+\log\cosh t\), \((1-\alpha)\log x\) and \(\log(1-x)\). Exponentiating this final quantity may underflow in sufficiently distant tails. There that represents a negligible weighted contribution, rather than the disappearance of the physical interval itself.
In an integral supplied by a black-box material law the algebraic combination may be less accessible. If the law can accept a distance and the logarithm of a distance, the same strategy works. If measurements stop before either endpoint, no quadrature transformation recovers information about the missing function automatically. A defensible result should record where the model was extrapolated as well as how the integration was performed.
Design two distinct convergence experiments
First vary the number of transformed panels at fixed half-window and plot the absolute error. Use absolute error near a zero integral because a relative percentage becomes ill-conditioned as the answer tends to zero. Next increase \(T\) while keeping the transformed step approximately fixed. More points are then added to the previously discarded tails. If changing the half-window matters and halving the step does not, the initial allocation spent too much effort in the centre. Repeat this reasoning before making claims about asymptotic convergence from only two almost identical values.
For this particular reference family there is an even simpler independent calculation: map \(x=u^{1/(1-\alpha)}\) on the unit interval. The diverging density and the vanishing derivative combine into the constant \(1/(1-\alpha)\). A single properly weighted node can integrate a constant exactly. This yields a stringent check of the implementation while illustrating a general design principle. When the singularity exponent is known and the remaining factor is smooth, a tailored substitution may be the easiest route to the required integral. Tanh–sinh is especially attractive when the two endpoints need protection and their detailed local structure is not fully known.
Compare two uses of a fixed sample budget
Take 33 transformed nodes and put 16 panels on either side of the origin. A half-window of two now gives a step of one eighth. Doubling the half-window with the same number of samples doubles the spacing while extending the tails. There is no general reason this second calculation should be more accurate. It trades centre resolution for coverage. Plot the estimates against window length at fixed sample count and identify the interval where both errors are small. Move the exponent closer to one and repeat; the useful window typically shifts because the physical edge carries a larger fraction of the signal.
For a more expensive black-box integrand, retain samples when halving the transformed step at fixed cutoff. All old abscissae lie on the finer grid. The trapezoid at the finer step is the sum of half the old approximation and the new midpoint samples times the finer spacing. This reuse affects computational cost, not the mathematics of the tail correction. It supports two separate reports: how much the estimated integral changed and how many genuinely new evaluations were required to obtain that change.
A local OneSimulation comparison in the notebook uses twenty-four line elements on the retained window. Eight mapped Gaussian points per element sample the transformed density at different locations from the trapezoid. Compare that sum with the analytical finite-window integral. Agreement here isolates the numerical integration on the interval. The previously calculated tails must still be included when reporting the complete physical signal.
Tutorial on endpoint mass and stopping criteria
1. An instrument cannot resolve the first millionth of the width. For \(\alpha=2/3\), what fraction of the total signal would be omitted if this strip were simply discarded?
Work through the solution
The fraction is \(\varepsilon^{1-\alpha}\). Substituting \(10^{-6}\) and \(1/3\) gives \(10^{-2}\), or one per cent. The full integral is three, so the omitted integral is 0.03 in the dimensionless units of the model. This error would persist even for an exact integration over the resolved remainder.
2. With \(\alpha=1/2\), compare the first-panel midpoint contribution to its exact value. What follows for the number of uniform panels needed merely to halve this contribution to the error?
Work through the solution
The exact value is \(2\sqrt h\), and the midpoint gives \(\sqrt{2h}\). Their difference is \((2-\sqrt2)\sqrt h\). To halve it one must quarter \(h\), hence quadruple the number of panels on the fixed overall interval. A second-order rule for a smooth function would suggest a much smaller increase.
3. Two calculations with \(T=2\) agree to ten printed digits. Does this suffice to report ten digits in the full integral? Propose an additional diagnostic for a density without a known antiderivative.
Work through the solution
Agreement supports resolution inside the selected window. Extend both tails at comparable step and record the changes from the new bands separately. Inspect their decay and, if the model supplies an asymptotic bound, integrate that bound beyond the last sampled band. Almost equal numbers at one truncation do not constrain a contribution that neither run sampled.
Further reading · Masatake Mori, discovery and development of the double-exponential transformation
Change parameters · Integrating an infinite endpoint with a finite table of samples
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 7 · Project · How many sensors measure the mean around a ring?
Design, challenge and repair a quadrature for periodic temperature measurements. Distinguish a sampled mean, reconstruction of a continuous profile and error in a reference calculation.
Predict three instrument readings
A manufactured test field is \(T(\theta)=20+2\cos(5\theta)+0.8\cos(12\theta)\) °C. Determine its exact spatial mean. Predict measurements from rings with 5, 6 and 7 equally spaced sensors at zero offset. Calculate their mean using a finite geometric sum.
Work through the solution
The continuous mean is 20 °C because both cosines integrate to zero over a full turn. For mode \(k\) set \(z=e^{2\pi i k/N}\). When \(z\ne1\), the discrete average is
When \(z=1\), every term is one. Taking real parts leaves only harmonics divisible by the sensor count. Five sensors see a mean of 22, six give 20.8 and seven give 20. These results describe three different instruments observing exactly the same field. A 12-sensor instrument also measures 20.8, so agreement with a coarser grid can be misleading.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Build a diagnostic from a second run
Turn the six-sensor ring by 15°. Determine which part of the signal changes in its mean. Can the average of the two runs recover the continuous mean? Test the 12th harmonic with the rotatable sensor ring. Its test harmonic has amplitude 3 °C. Compare the sign reversal and rescale its mean offset by 0.8/3 to match this instrument.
Work through the solution
The twelfth harmonic changes sign since \(12(15^\circ)=180^\circ\). The fifth harmonic still averages to zero. The second mean is 19.2 °C; the two-run average is 20. The offset is a quarter of the old sample interval. A half-interval rotation of 30° would bring the twelfth harmonic through a full cycle and keep the erroneous mean. Choose offsets using the alias you intend to diagnose.
Use an interval integral for an independent calibration
A second sensor samples a reference profile \(u(x)=x^4\) along a straight rail with scaled coordinate \(0\le x\le1\). On one, two and four equal panels its trapezoidal values are 0.5, 0.28125 and 0.220703125. Build the first two extrapolation columns. Then change the exponent to one half in the extrapolation experiment. Explain where using the wrong error power would distort the calibration.
Work through the solution
Two first extrapolates are
Combining them with denominator 15 gives 0.2. The square-root profile lacks a bounded derivative at the endpoint, so a full even-power error expansion cannot be assumed. The observed convergence ratio is the diagnostic in this run.
State what the specification guarantees
The design must integrate any trigonometric polynomial with modes through 12 and also reconstruct it uniquely if asked. Find sufficient uniform sensor counts for each task and explain their difference.
Work through the solution
A 13-point ring integrates all these modes exactly because none of \(1,\ldots,12\) is divisible by 13. To recover all sine and cosine coefficients through mode 12 one needs \(2(12)+1=25\) real degrees of freedom. A 25-point uniform ring suffices. The mean is a single linear functional and can be identifiable when the full field is not.
Explore the related calculation with adjustable inputs. Change the parameters in the corresponding calculation and compare its independently recomputed values with the equation derived in this solution.
Problem sheet 8 · Integrate a rapidly oscillating signal without resolving every crest
A lock-in detector measures the in-phase integral \(I(k)=\int_0^1 f(x)\cos(kx)\,dx\). The carrier frequency is known exactly from the instrument. The envelope is smooth and expensive to evaluate. Design a quadrature rule that spends those evaluations on the envelope, and find a case where even the improved method gives a deceptively small answer.
Predict a complete alias on a coarse scan
Let \(f(x)=1+x^2\) and \(k=16\pi\). Use eight uniform panels and include both endpoints with half weight in the trapezoidal rule. What does the instrument predict, and what is the true integral?
Work through the solution
The carrier completes exactly one full cycle per panel. Its values at every sampled point are therefore one, so the naive sum integrates only the envelope. It gives
Integrating the oscillatory expression by parts twice gives
At \(16\pi\) the true result is
The small true signal comes from cancellation of lobes with slightly unequal envelope weights. Nothing in the sampled carrier values reveals those lobes. A small residual between the trapezoidal estimates of a few adjacent sampled segments would be uninformative here.
Explore the related calculation with adjustable inputs. Change the parameters in the experiment on this same project page and compare its output with this part of the derivation.
Record which quantities are known before choosing a rule. If the underlying carrier were unknown and only sampled instrument voltages were available, this example would be an information problem: the samples are also consistent with an unmodulated envelope. Here the oscillator frequency and phase are controlled and available between sample positions. A numerical method can exploit that extra knowledge without evaluating the expensive part of the integrand any more frequently.
Integrate a linear envelope against the exact carrier
Approximate only the envelope on a panel of width \(h\) and midpoint \(m\) by \(a+bt\), where \(t=x-m\). Find \(a,b\) from endpoint samples and derive the exact panel integral of this approximation.
Work through the solution
Use \(a=(f_L+f_R)/2\), \(b=(f_R-f_L)/h\), and set \(d=kh/2\). Expand \(\cos[k(m+t)]\) into cosine and sine products. Odd integrands integrate to zero on the symmetric interval. The constant part gives \(2a\cos(km)\sin d/k\). The slope term gives \(-2b\sin(km)(\sin d-d\cos d)/k^2\), after an integration by parts of \(t\sin(kt)\). Add the two terms and sum over panels. This is a piecewise-linear member of the Filon family: interpolate a slowly varying amplitude and compute its oscillatory moments. It integrates every globally linear envelope exactly for every carrier frequency, up to roundoff.
Explore the related calculation with adjustable inputs. Change the parameters in the experiment on this same project page and compare its output with this part of the derivation.
The individual moment expressions require care when \(d\) is very small. In particular \(\sin d-d\cos d=d^3/3-d^5/30+\cdots\); evaluating it by direct subtraction near zero loses significant digits. In the limit \(k\to0\) the constant moment becomes \(h\), the odd contribution vanishes, and the rule reduces to an ordinary trapezoid for the envelope. For high frequency the same formula behaves quite differently from sampling the product. The analytic moments retain the signs and magnitudes of oscillatory contributions between the nodes.
Explain an apparently perfect zero and recover curvature
Return to eight complete periods on eight panels. The fitted linear rule now gives zero. Is this answer exact? What new measurement can recover the missing signal?
Work through the solution
Here \(d=\pi\) and \(\sin(km)=0\) on every panel. Both moment contributions vanish separately, regardless of the endpoint amplitudes. The constant and linear parts of each local envelope make no net contribution over a centred complete cosine period aligned this way. The exact quadratic curvature does contribute. Introduce one midpoint envelope measurement and fit a quadratic through the endpoints and midpoint; its exact oscillatory second moment recovers the polynomial test identically. On these aligned panels a simpler check is to compute the residual \(f(x)-p_1(x)=(x-x_L)(x-x_R)\). The integral of its quadratic term supplies exactly the signal discarded by the linear rule. The linear answer is far closer in absolute terms than the aliased trapezoid, yet its relative error for the small target is still one hundred percent.
Explore the related calculation with adjustable inputs. Change the parameters in the experiment on this same project page and compare its output with this part of the derivation.
Dimensional reasoning makes the restoration plausible. For a twice differentiable amplitude the pointwise error of linear interpolation on one panel is bounded by \(\max|f''|h^2/8\). Multiplying by \(|\cos|\le1\) and integrating across all panels yields a uniform absolute error bound of the same order on this unit interval. It says little about relative error when the exact integral is a small difference of much larger signed contributions. An acceptance criterion for a detector with a known noise floor should therefore include an absolute tolerance expressed in the actual output units.
Test resolution and report a useful tolerance
Vary the number of panels and sweep the carrier through adjacent frequencies in the live graph. Which measurements distinguish genuinely small coherent output from values produced by aliasing?
Work through the solution
Compute an independent reference by integrating the polynomial test analytically. Compare absolute errors on both sides of an integer number of cycles, including the exact alignment at eight cycles. The aliased trapezoid produces peaks when sampled phases line up. The Filon result follows the reference more closely once the envelope is resolved, with the special zero at the exactly aligned coarse case explained above. Repeat after doubling panel count and changing the start phase in an actual experiment. The true in-phase projection also changes with phase, so compare against the corresponding analytic reference for that phase instead of demanding agreement between physically different projections.
Explore the related calculation with adjustable inputs. Change the parameters in the experiment on this same project page and compare its output with this part of the derivation.
The graph displays integrals versus the number of carrier cycles, holding the number of envelope panels fixed over the sweep. Start with eight panels and include the neighbourhood of eight cycles. Then increase the panel count to sixteen. Read the signed reference and the two calculated estimates at the selected frequency. A rapidly oscillating but known carrier is a structural clue: a rule using its exact moments and an independently tested envelope approximation can avoid catastrophic sampling aliases.
L. N. G. Filon's original paper on quadrature for trigonometric integrals.
Notebook practice · Integrating an infinite endpoint with a finite table of samples
Function approximation and numerical integration
Construct approximations from the information actually available. Derive their error and observe what changes when the function, data or sampling rule violates an assumption.
- Approximating a resonance with a rational function
A smooth response on a measured interval can be governed by a nearby pole. Derive a low-order Padé fit, construct a barycentric rational approximant from samples and check whether a predicted pole survives independent data.
- Integrating cosine interpolants on nested grids
Chebyshev points turn polynomial interpolation into a cosine series. Derive the exact moments of each basis polynomial, explain aliasing and find a case where two consecutive quadrature grids confidently agree on the wrong answer.
- Integrate the oscillations analytically and sample the envelope
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.
- Spend random samples where they reduce uncertainty
A Monte Carlo estimate can be unbiased and still too noisy to be useful. Derive control variates, allocate a fixed budget across strata, and distinguish variance reduction from an underestimated standard error.
- How many neighbouring samples belong in a slope estimate?
A wider local fit suppresses measurement noise, yet it can smooth away real changes in slope. Derive the competing errors, then use noisy synthetic data to find which differentiator wins at a chosen spacing.
- What can smoothness buy at a fixed polynomial degree?
Prove density for every continuous signal, derive a faster rate for smooth signals and identify the persistent overshoot when a jump violates the assumptions.
- When should the denominator be fitted too?
Develop a minimax certificate for rational approximants, find the pole of a measured response and identify the obstruction that appears when a trial denominator vanishes inside the interval.
- Measuring an area integral with finitely many samples
Build deterministic multidimensional rules from moments and geometry. Compare tensor products, symmetric triangle rules and sparse combinations at a fixed number of evaluations.
Function approximation and numerical integration · 1. Approximating a resonance with a rational function
A smooth response on a measured interval can be governed by a nearby pole. Derive a low-order Padé fit, construct a barycentric rational approximant from samples and check whether a predicted pole survives independent data.
Match series coefficients without requiring a polynomial model
Let \(f(x)=c_0+c_1x+c_2x^2+\cdots\) near zero. A polynomial Taylor approximation fixes coefficients but cannot represent a finite pole. A type \([m/n]\) Padé approximant \(P_m(x)/Q_n(x)\) uses polynomials of degree at most \(m,n\), and fixes the arbitrary common scaling by \(Q_n(0)=1\) where possible. Require
For powers above \(m\) the unknown numerator cannot contribute; they give linear equations \(\sum_{j=0}^n q_jc_{k-j}=0,\ k=m+1,\ldots,m+n\) for the denominator, with missing negative-index coefficients taken zero. Lower coefficients then give
Although the desired quotient is nonlinear in its coefficients, series matching has reduced the construction to linear algebra.
For \(f=e^{-x}\), matching \(1-x+x^2/2\) gives
Its expansion agrees through second degree; at \(x=1\) it gives \(1/3\), compared with \(e^{-1}=0.3679\) and Taylor degree two \(0.5\). But the rational has a pole at \(-2\) even though the exponential is entire, and becomes negative for \(x>2\). A good local approximation does not establish that every pole corresponds to physical resonance or every extrapolated value respects a known constraint such as positivity. The model's domain and validation data determine the legitimate interpretation.
Interpolate at selected support points while fitting other samples
When samples, rather than derivatives at one origin, are available, a barycentric form is convenient:
At a support node use the exact stored \(f_j\), interpreting the apparent singularity by its limit when \(w_j\ne0\). Common rescaling of all weights leaves \(r\) unchanged. For another data pair \((z_i,f_i)\), a small cross-multiplied discrepancy requires \(\sum_jw_j(f_i-f_j)/(z_i-z_j)\approx0\). With several unsampled points this is a homogeneous least-squares problem for the weights; impose unit norm and take the right singular vector belonging to the smallest singular value. The adaptive AAA algorithm selects an additional support point where current error is large and rebuilds this fit until a stopping criterion is met.
The cross-multiplied error and true value error differ by the rational denominator. A very small denominator can amplify a small algebraic residual, so validate the fitted quotient directly on independent points and check for poles in the intended domain. Closely paired numerator and denominator roots can almost cancel. Such a weak-residue pole–zero pair can encode numerical noise rather than a well-resolved physical mode. Testing another grid, another noise realisation and the residue is more informative than printing every computed root with equal confidence.
Compare local and global descriptions on a known response
Take \(f(x)=1/(1+\beta x^2)\) for \(\beta>0\). Its poles are at \(x=\pm i/\sqrt\beta\), outside the real line but at a finite distance from the origin. The even Taylor series is geometric in \(-\beta x^2\). Through power \(x^{2m}\) the relative error magnitude is \((\beta x^2)^{m+1}\). It converges for \(|x|<1/\sqrt\beta\), fails to converge outside that radius and can show oscillatory partial values across a perfectly smooth real measurement interval. Its type \([0/2]\) rational reconstruction from \(c_0=1,c_1=0,c_2=-\beta\) is exact in noiseless arithmetic. That success rewards a model family matching the analytic structure; it does not imply unknown response functions must have just this pair of poles.
Compare a Taylor and a rational continuation
The plot holds the rational response above as known truth. Vary the pole distance through \(\beta\), then change the polynomial truncation. Watch where increasing the expansion order improves agreement and where it worsens it. A noisy curvature estimate changes the fitted rational pole locations; use the readout to compare the pole error with the predicted local change. The experiment intentionally exposes the truth, which is unavailable for a real instrument and must be replaced by out-of-sample checks.
Test the assumed response law on an unused reading
A value away from the centre tests curvature without differentiating noisy samples. Under the assumed normalisation \(f(0)=1\), solving \(y=(1+\beta x^2)^{-1}\) gives
At \(x=1/2\), a reading \(y=10/13\) yields \(\beta=1.2\). Before including any other reading, predict \(f(1)=5/11\). A measured value of \(0.50\) differs by about \(0.0455\). More Taylor coefficients of the fitted rational function all inherit the same discrepancy. They cannot establish an independent agreement.
The derivative of the inferred parameter with respect to a measured value is \(-1/(x^2y^2)\). At the calibration point its magnitude is \(6.76\). An absolute measurement uncertainty of \(0.005\) propagates to about \(0.034\) in \(\beta\), and then about \(0.0070\) in the predicted reading at one. A disagreement of \(0.0455\) would warrant examining calibration of the unused reading, the assumed normalisation and the model itself. Comparing two computed continuations built from the same reading would miss this test.
Tutorial · separate a useful fit from a physical pole
Infer a relaxation constant from two Taylor coefficients
A response starts \(f(s)=4-6s+9s^2+\cdots\). Construct a type \([0/1]\) fit and test the next coefficient rather than using it to determine the parameter.
Work through the solution
The constant numerator is 4 and \(4/(1+qs)=4-4qs+4q^2s^2+\cdots\). Matching slope gives \(q=1.5\) and predicted quadratic coefficient 9, consistent with the extra observation. The pole is \(-2/3\) in the units of \(s\). A further measured coefficient or a separate frequency interval can test the single-pole model. Agreement of three coefficients alone does not preclude additional weak modes.
Calculate a pole from two barycentric nodes
Use nodes \(z_1=0,z_2=1\), samples \(1,1/2\) and weights \(1,-2\). Simplify the quotient and locate its pole. What happens at the support nodes?
Work through the solution
Multiplying numerator and denominator by \(z(z-1)\) gives numerator \((z-1)-z=-1\) and denominator \((z-1)-2z=-z-1\). Hence \(r=1/(1+z)\), with pole at \(-1\). The original sums are singular separately at 0 and 1, but their limits give exactly 1 and \(1/2\). Direct numerical evaluation should return stored values at support nodes rather than form infinity divided by infinity.
Estimate the sensitivity of an inferred pole distance
The sampled response yields curvature coefficient \(-\beta=-4.0\pm0.4\). Infer the distance of the conjugate poles and its linearised relative uncertainty. Would this prove the real system has that exact physical singularity?
Work through the solution
The fitted distance is \(\beta^{-1/2}=0.50\), with relative uncertainty approximately \(\tfrac12(0.4/4.0)=5\%\), or absolute 0.025. A systematic error in the assumed response shape can dominate this local parameter uncertainty. Test independently sampled values farther from zero, compare alternative rational orders, and examine whether pole positions and residues persist. Noise estimates conditional on one chosen model are not a proof of analytic structure.
Further reading
Function approximation and numerical integration · 2. Integrating cosine interpolants on nested grids
Chebyshev points turn polynomial interpolation into a cosine series. Derive the exact moments of each basis polynomial, explain aliasing and find a case where two consecutive quadrature grids confidently agree on the wrong answer.
Use a change of coordinate to simplify both the grid and the basis
The Chebyshev polynomial \(T_k(x)\) is defined by \(T_k(\cos\theta)=\cos(k\theta)\). For \(N+1\) nodes \(x_j=\cos(j\pi/N)\), sampling a degree-\(N\) polynomial in Chebyshev coordinates becomes sampling a finite cosine series at equally spaced angles. A discrete cosine transform computes the unique interpolant's coefficients without a Vandermonde solve. Clenshaw–Curtis quadrature integrates that interpolant over \([-1,1]\). The integral is unweighted \(dx\), so in angle coordinates there is a \(\sin\theta\) Jacobian; it is not merely the trapezoidal average of the sampled values over angle.
Let \(I_k=\int_{-1}^1T_k(x)dx=\int_0^\pi\cos(k\theta)\sin\theta\,d\theta\). Odd \(k\) gives zero by parity. Using a product-to-sum identity for even \(k\) gives \(I_k=2/(1-k^2)\), including \(I_0=2\). With coefficients in the convention \(p_N=\sum_{k=0}^N a_kT_k\), the quadrature is simply
Some DCT implementations store doubled endpoint coefficients. Convert to the polynomial convention before using these moments; otherwise even the constant function can integrate to four instead of two. A quick audit is exact integration of \(1,x,x^2\) where the grid supports those degrees.
Explain why unsampled higher modes can imitate low modes
At sampling angles \(\theta_j=j\pi/N\), \(\cos[(2N-k)\theta_j]=\cos(k\theta_j)\) for integer \(j\). Frequencies folded about multiples of \(2N\) are indistinguishable on this grid. A single basis function \(T_{2N-k}\) consequently yields the same interpolant and quadrature as \(T_k\), even though the exact integrals differ. At \(N=8\), \(T_{14}\) aliases to \(T_2\), so \(Q_8=-2/3\) while the exact integral is
At \(N=16\) the polynomial is fully resolved and integrated exactly. Many practical smooth integrands have rapidly decaying high-mode coefficients, limiting this effect; smoothness without a quantitative resolution check is insufficient.
The error for a convergent Chebyshev expansion can be analysed as a sum of high-mode coefficients times differences between true and aliased moments. The even moments decay roughly as \(k^{-2}\), so exact integration of many high modes contributes little, but a high mode folding to \(T_0\) can cause a large erroneous contribution. This helps explain how a rule exact for degree only \(N\) can often perform competitively with Gaussian quadrature while still suffering carefully designed aliasing failures. Number of exact polynomial moments and actual performance on an analytic function are different comparisons.
Reuse data under refinement while looking for unresolved structure
Doubling the number of intervals gives \(x_{2j}^{(2N)}=x_j^{(N)}\), so all previous samples can be reused. This is valuable when evaluating one function call involves a time-dependent model or laboratory observation. For a general interval \([a,b]\), map \(x\) affinely and multiply every integral by \((b-a)/2\). Compare successive \(Q_N\), decay of the latter Chebyshev coefficients and an independent nonnested or local check. If the integrand has an unresolved local spike or frequency intentionally locked to the grid, two nested results can agree spuriously.
For a diagnostic let \(f=T_{4N}\). Both the \(N\)- and \(2N\)-interval grids sample the constant value one, so both return 2 despite the exact integral \(2/(1-16N^2)\) being small and negative. Once the \(4N\)-interval grid resolves the highest polynomial the answer changes dramatically. This does not imply nested algorithms should always quadruple a mesh unquestioningly. When physical bounds on derivatives, a known bandwidth or local event locations are available, use them to select an initial resolution and targeted check. Without such information no deterministic finite sampling can certify arbitrary unknown integrands.
Background · Can two consecutive nested rules agree on the wrong integral?
Use the Chebyshev polynomial \(T_{4N}(x)\) on \([-1,1]\). On the fine grid \(x_j=\cos(j\pi/(2N))\), its sampled values are \(\cos(2j\pi)=1\). The coarse grid is a subset and sees exactly the same constant. Both rules consequently return the integral of one, namely 2. But the unweighted integral follows by setting \(x=\cos\theta\) and integrating \(\sin\theta\cos(4N\theta)\):
At \(N=4\) both sampled estimates are 2 while the actual integral is \(-2/255\). An independent off-grid evaluation, or a refinement sequence chosen using prior frequency information, can expose the oscillation. This example pinpoints which assumption a difference-based stopping test needs: the current samples must already represent the significant scales.
Make two nested rules agree on a false integral
Take eight coarse intervals and choose degree 32. Read the two interpolated moments and derive the correct integral analytically. At degree 31 both rules also agree. Explain why they are now exact. At degree 16 determine which grid returns 2 and which resolves the true moment. What evidence distinguishes symmetry from a spurious agreement due to aliasing?
Tutorial · inspect coefficients and stopping signals
Build a three-point rule from moments
With \(N=2\) the nodes are \(1,0,-1\). Use symmetry and moments of \(1,x^2\) to obtain the weights. Integrate \(x^4\) and explain the error.
Work through the solution
Symmetry gives endpoint weights \(w\) and centre weight \(v\). Exactness of the constant requires \(2w+v=2\); for \(x^2\) it gives \(2w=2/3\), hence
The estimate for \(x^4\) is \(2/3\) whereas the exact integral is \(2/5\), an error of \(4/15\). Although the rule integrates odd cubics by symmetry, polynomial degree four is not guaranteed. Expanded in Chebyshev modes, its unresolved \(T_4\) aliases to the constant.
Derive the error caused by one small high-frequency contaminant
At \(N=8\) a signal is \(1+0.01T_{16}\). Compare the sampled integral with the exact one and inspect a second grid with 16 intervals.
Work through the solution
Every coarse node samples 1.01, yielding 2.02. The exact integral is
The error around 0.0201 is large relative to the true high-mode integral because its samples look constant. At 16 intervals the true mode is represented, giving the exact value up to roundoff. A small-amplitude frequency component can contribute disproportionately to a coarse low-mode estimate when it aliases.
Determine whether an adaptive error diagnostic has a rigorous guarantee
Two nested rules agree to \(10^{-10}\) and all computed high coefficients are small. Does that certify the integral for an otherwise unconstrained analytic function? Construct an explicit counterexample.
Work through the solution
At any fixed finite \(N\), the polynomial \(T_{4N}\) above is analytic and all coarse coefficients except the constant vanish on both grids. Adding a multiple of \(T_{4N}-1\) to an arbitrary candidate leaves both sampled grids unchanged but shifts its exact integral by nearly minus twice that multiple. Thus agreement is evidence conditional on a smoothness or scale model, not an unconditional bound over every analytic function. A genuine analytic error theorem also needs quantitative information such as a bound on an analytic continuation region and its magnitude.
Further reading
Function approximation and numerical integration · 3. Integrate the oscillations analytically and sample the envelope
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.
Estimate an oscillatory integral before choosing a grid
Consider \(I(\omega)=\int_a^b f(x)e^{i\omega x}dx\) with smooth envelope \(f\) and known constant phase slope. The complex result contains cosine and sine transforms as real and imaginary parts. Direct quadrature can work if the grid resolves both envelope and oscillation. But a uniform grid with spacing \(h=2\pi/\omega\) samples the same complex phase at every point and can report a large entirely spurious response. A calculation accurate for the slow envelope alone need not be accurate for its product with the carrier. The explicit oscillating factor contains information we can integrate analytically rather than sampling it repeatedly.
Integration by parts gives
For bounded derivatives the integral is typically \(O(1/\omega)\) at high frequency, and endpoint cancellations or endpoint vanishing can improve the decay. A result as large as \(\int |f|dx\) at a very high frequency is therefore suspicious unless the phase has a stationary point, rapid structure exists in the envelope or a special physical resonance changes the setup. Absolute error is a better validation measure near an exact transform zero than relative error, which divides by a possibly vanishing number.
Derive a two-node Filon panel about its midpoint
On a panel \(x=c+s,\ -h\le s\le h\), approximate the envelope by \(A+Bs\) through its endpoints, with \(A=[f(c+h)+f(c-h)]/2\) and \(B=[f(c+h)-f(c-h)]/(2h)\). Retain the carrier exactly. Define \(z=\omega h\). Its zeroth moment is
Differentiating with respect to \(\omega\) gives \(\partial_\omega M_0=i M_1\), so
\(M_0\) is real and even in frequency and \(M_1\) imaginary and odd, as symmetry requires. The rule is exact for every linear envelope at every frequency, regardless of the number of oscillations in the panel. At \(\omega=0\) it returns the trapezoidal integral of the linear interpolant. Directly subtracting \(\sin z-z\cos z\) for tiny \(z\) loses precision. Instead use its series \(z^3/3-z^5/30+\cdots\), and evaluate \(\sin z/z\) by a stable sinc routine or a short series near zero.
For \(f(x)=1+x,\ x\in[0,1]\) and \(\omega=20\pi\), the constant contribution vanishes over ten cycles. Integration by parts on \(x\) gives
One linear Filon panel gives the exact \(-0.0159155i\). A composite trapezoid with ten subintervals samples \(e^{i\omega x}=1\) at every node, returning 1.5 real. Both methods evaluated the same envelope but represented the carrier quite differently. Refining blindly by factors that preserve a frequency coincidence can produce misleading error estimates on the first few grids.
Separate envelope approximation from phase modelling
Since the carrier has magnitude one for real phase, \(|I-Q|\le\int|f-p|dx\). A piecewise-linear interpolation error bound on a panel of width \(H\) is \(\max|f''|H^2/8\), giving a global absolute bound \((b-a)\max|f''|H^2/8\) independent of \(\omega\). Oscillatory cancellation can make the actual error much smaller, but this bound already identifies a sensible grid criterion based on envelope curvature. Higher-order Filon methods integrate more polynomial moments or use derivatives at endpoints. Stable moment recurrences and consistent treatment near \(\omega=0\) matter as much as theoretical order.
For a nonlinear phase \(e^{i\omega g(x)}\), changing variable to \(u=g(x)\) can reduce to a linear phase on a monotone interval, with transformed envelope \(f(x(u))/g'(x(u))\). At a stationary point \(g'=0\) this substitution becomes singular. In that case oscillations slow locally and the contribution can decay as \(\omega^{-1/2}\) for a simple quadratic stationary point, often larger than endpoint terms. Splitting the domain and using a local quadratic-phase or stationary-phase treatment is more informative than declaring the original linear-phase rule universally efficient. Identify the physical phase law before attributing a numerical discrepancy to envelope smoothness.
Make a fast carrier invisible to the sampling grid
The envelope is exp(x) on the unit interval. Keep six integration panels and select six carrier cycles. Every direct trapezoidal sample sees a cosine of one. Over each full cycle both a constant and a linear envelope have zero cosine integral here. Why does the curved exponential still give 0.0012082? Change to seven panels at the same frequency and compare absolute errors. Finally set the frequency to zero: both methods integrate the same piecewise-linear envelope, so their common value can still differ from the exact integral.
Tutorial · check the carrier convention and asymptotic scale
Integrate a symmetric odd envelope
For \(f(x)=x\) on \([-1,1]\) and \(\omega=\pi\), compute \(I\) from the first moment. Which part vanishes?
Work through the solution
Use \(h=1,c=0,A=0,B=1\). Since \(\sin\pi=0,\cos\pi=-1\), \(I=2i/\pi\). The cosine part vanishes by parity and \(x\sin(\pi x)\) is nonnegative on both sides, confirming the positive imaginary sign. Using a Fourier convention \(e^{-i\omega x}\) instead would conjugate the result. A test on this odd envelope detects a sign error that any even real envelope would miss.
Give a sufficient interpolation-based error budget
On a unit interval a calibrated envelope obeys \(|f''|\le6\). How many equal panels suffice for absolute error \(10^{-4}\) using the elementary bound? Does doubling frequency change the stated count?
Work through the solution
The bound is \(6/(8N^2)\). Requiring it at most \(10^{-4}\) gives \(N\ge\sqrt{7500}\), so 87 panels suffice. The bound makes no frequency assumption beyond a known real linear phase and does not require more panels merely because frequency doubles. Floating-point phase reduction for extremely large arguments and uncertainty in the physical frequency are separate sources of error not included in the envelope bound.
Estimate sensitivity to a miscalibrated frequency
Show that a frequency error \(\delta\omega\) can perturb the integral by at most \(|\delta\omega|\int|x f(x)|dx\). Evaluate for the previous \(f=1+x\) on \([0,1]\) and \(|\delta\omega|=0.01\).
Work through the solution
Differentiate under the integral to obtain \(I'(\omega)=i\int x f(x)e^{i\omega x}dx\), then bound its norm and integrate over the frequency error. Here \(\int_0^1x(1+x)dx=5/6\), giving an absolute perturbation at most 0.00833. Relative to the small exact response at \(20\pi\), this can be substantial. An exactly integrated carrier on the wrong frequency is therefore not a high-accuracy physical prediction merely because the quadrature test is exact.
Further reading
Function approximation and numerical integration · 4. Spend random samples where they reduce uncertainty
A Monte Carlo estimate can be unbiased and still too noisy to be useful. Derive control variates, allocate a fixed budget across strata, and distinguish variance reduction from an underestimated standard error.
Subtract a fluctuation with an independently known mean
To estimate \(I=\mathbb E[f(X)]\), suppose evaluating \(f(X)\) also supplies a cheap correlated quantity \(g(X)\) with known exact mean \(\mu_g\). For any fixed coefficient \(\beta\), \(Y=f(X)-\beta[g(X)-\mu_g]\) has the same mean \(I\). Its variance is \(V_f-2\beta C_{fg}+\beta^2V_g\). Differentiating gives optimum \(\beta_*=C_{fg}/V_g\) if \(V_g>0\) and minimum \(V_f(1-\rho_{fg}^2)\). For a crude physical surrogate it is accuracy of its fluctuations, not its absolute scale, that matters. A negatively correlated surrogate can also reduce variance by a negative coefficient. A constant control carries no information and should not be divided by zero variance.
As an exact example take \(X\sim U[0,1]\), \(f=X^2\), \(g=X\). We know \(\mu_g=1/2\) and seek \(I=1/3\). Direct moments give
Hence \(\beta_*=1\) and residual variance \(4/45-1/12=1/180\), sixteen times smaller than the original. At the same sample count the standard deviation falls by four. Each controlled sample \(X^2-X+1/2\) is not equal to the true answer, but it fluctuates much less. An independent pilot run can estimate \(\beta\) for unknown covariances. Reusing the same small sample to optimise \(\beta\) and estimate the mean can introduce finite-sample bias and overstate achieved variance reduction, especially when many controls are fitted.
Partition the input space and allocate observations
Divide the domain into disjoint strata with known probabilities \(w_j\), then draw \(n_j\) independent observations within each. The stratified estimator is \(\hat I=\sum_j w_j\bar f_j\) with variance \(\sum_jw_j^2\sigma_j^2/n_j\), where \(\sigma_j^2\) is the conditional variance. Correct weighting is crucial: the allocation probabilities need not equal the target distribution's stratum probabilities. At a fixed total sample count \(N=\sum n_j\), differentiating with a Lagrange multiplier gives \(n_j\propto w_j\sigma_j\), known as Neyman allocation. For unequal sample costs \(c_j\) under fixed \(\sum c_j n_j\), the corresponding optimum is \(n_j\propto w_j\sigma_j/\sqrt{c_j}\). Pilot uncertainty and minimum counts per stratum matter before rounding to feasible integers.
For two equal-probability strata with conditional standard deviations 1 and 4, \(N=100\) calls yields optimal counts 20 and 80. The variance becomes \((1/4)(1/20+16/80)=0.0625\), compared with \(0.085\) from 50 each. The difference is material but smaller than one might guess from the 4:1 standard deviation ratio. Overallocating all observations to the difficult stratum would leave the other conditional mean unidentified. A deterministic stratum whose mean is known separately can be removed; one whose variance merely looked zero in a tiny pilot may still need independent sampling. For rare heavy-tail excursions, a naive pilot can miss the very fluctuations it was intended to characterise.
Choose an antithetic pair with a justified covariance
For symmetric \(U\sim U[0,1]\), both \(U\) and \(1-U\) have the target distribution. The pair average \(Z=[f(U)+f(1-U)]/2\) is unbiased. Its variance is \([V_f+\operatorname{cov}(f(U),f(1-U))]/2\). With the same two function evaluations, two independent samples would have variance \(V_f/2\). Antithetic pairing therefore helps exactly when the paired function values are negatively correlated, as with a monotone function over this scalar interval. If \(f(U)=f(1-U)\) the pair is redundant; the method then doubles cost per independent value. Compute standard errors across independent pairs, not by treating both values inside each pair as independent calls.
For \(f=X^2\), \(Z=X^2-X+1/2\), algebraically the same controlled random variable encountered above. Its variance is \(1/180\) per pair and it costs two evaluations. The linear control cost only one expensive \(f\) evaluation when \(g=X\) was nearly free. The two methods yield identical random fluctuations per independent draw of \(X\) here, but different error per unit computation. Comparing only the algorithm's reported sample count without accounting for pairs, pilot runs and surrogate evaluations can reverse a practical recommendation.
When does the control increase the noise?
Draw X uniformly on the unit interval and estimate the mean of X². The known mean of X is one half. Compare the standard errors at coefficients zero, one and three. Use the graph to find how many direct samples match the uncertainty of 32 optimally controlled samples, then confirm the answer from the exact variance ratio.
Tutorial · verify variance and bias separately
Budget calls with a measured correlation
A model response has standard deviation 6 and a validated fixed-coefficient control has correlation 0.95. Estimate calls for standard error 0.10 with and without control, neglecting control cost.
Work through the solution
Plain sampling requires \(6^2/0.1^2=3600\) independent calls. The controlled variance is \(36(1-0.95^2)=3.51\), requiring 351 independent calls. These counts assume the reported correlation and optimal coefficient apply to the production distribution. Validate with held-out paired observations. A mistaken known control mean introduces bias \(\beta(\mu_{\rm used}-\mu_{\rm true})\), which averaging more calls cannot remove.
Find the cost-aware allocation
Two equal-probability strata have standard deviations 1 and 4. Calls in the second cost four times those in the first. Allocate 180 cost units, measuring cheap calls in units of one.
Work through the solution
The optimum ratio \(n_2/n_1=(4/\sqrt4)/(1/\sqrt1)=2\). With \(n_1+4n_2=180\) this gives
Their variance is
Assigning half the calls to each would instead permit 36 and 36 with variance about 0.118. Assigning half the budget to each gives a different allocation again. Specify the constrained physical resource before quoting an optimum.
Identify an antithetic failure and repair the error estimate
For \(f(x)=(x-1/2)^2\), an analyst generates 100 independent antithetic pairs but computes an ordinary sample error as though all 200 values were independent. What is wrong?
Work through the solution
Each pair consists of identical function values. There are only 100 independent observations of this response; the variance of the paired estimator is \(V_f/100\), whereas the false independent count suggests \(V_f/200\). Estimate uncertainty from the variance of the 100 pair averages or use 200 genuinely independent calls if possible. Here the pairing has no cancellation because the function is symmetric under precisely the transformation used to generate the second member.
Further reading
Function approximation and numerical integration · 5. How many neighbouring samples belong in a slope estimate?
A wider local fit suppresses measurement noise, yet it can smooth away real changes in slope. Derive the competing errors, then use noisy synthetic data to find which differentiator wins at a chosen spacing.
Fit a polynomial in local coordinates
Suppose we observe \(y_j=f(jh)+\epsilon_j\) at equally spaced times around zero. The errors are independent with mean zero and common standard deviation \(\sigma\). Fit \(a+bx+cx^2\) by minimizing the sum of squared differences on five points with \(j=-2,-1,0,1,2\). Differentiate that sum with respect to \(b\). Because \(\sum j=\sum j^3=0\), the odd column of the design matrix is orthogonal to both even columns. The fitted slope is therefore
Its weights have zero sum and give exactly one on a unit linear ramp. A quadratic term cancels by symmetry. A cubic term \(\beta x^3\) contributes \(\beta h^2\sum j^4/\sum j^2=3.4\beta h^2\) to the estimate. Meanwhile the independent noise variances add after weighting. Their sum is \(\sigma^2/(10h^2)\). For a three-point fit the same calculation gives a cubic bias of \(\beta h^2\) and a variance of \(\sigma^2/(2h^2)\).
Write the leading bias as \(Bh^2\) and the noise standard deviation as \(S/h\). The mean square error around the true derivative is \(B^2h^4+S^2/h^2\). Its minimum is at \(h=(S^2/(2B^2))^{1/6}\) when both contributions are present. Repeated noisy measurements could reduce the noise term too. Correlated measurement errors require the covariance matrix between samples in the variance calculation.
Diagnose a surprising result at two spacings
Use a signal \(f(x)=1+x+0.4x^2+x^3\) and noise standard deviation 0.02. The target derivative at zero is one. At \(h=0.20\) the five-point bias is 0.136 and its noise standard deviation is about 0.0316, giving a root mean square error of 0.1396. The three-point bias is 0.040, its standard deviation is 0.0707 and its total error is 0.0812. The shorter fit wins despite its greater sensitivity to random noise.
At \(h=0.08\) the five-point values change to 0.02176 and 0.07906, giving a total of 0.0820. The three-point result is about 0.1769. Changing the spacing has exchanged the dominant source of error. A single realization can put its estimate on either side of the derivative. Change the random seed while keeping the spacing fixed to distinguish this variability from the average error in the second plot.
Open full-size diagram
Open full-size diagramExercise · predict a single perturbation
A five-point experiment at spacing 0.2 measures the rightmost sample 0.03 above its true value. By how much does that change the slope? What happens if the same offset appears on all five samples?
Work through the solution
The rightmost derivative weight is \(2/(10h)=1\) in these units. The slope rises by 0.03. A common offset contributes its magnitude times the sum of all weights, which is zero. This cancellation also explains why an uncertain but constant instrument zero does not affect this derivative.
Exercise · choose a spacing when noise increases
If an otherwise identical experiment has eight times the noise standard deviation, how should the optimum spacing change? Will this scaling hold for a perfectly quadratic signal?
Work through the solution
With fixed cubic coefficient \(B\), the optimum is proportional to \(\sigma^{1/3}\). Eight times the standard deviation therefore doubles the best spacing. For a quadratic the cubic bias vanishes identically. The stated model then predicts decreasing noise error as the spacing grows. In a real record the usable window can be limited by unmodelled higher derivatives, nearby boundaries or changing noise statistics.
Change parameters · Explore this notebook model
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.
Function approximation and numerical integration · 6. What can smoothness buy at a fixed polynomial degree?
Prove density for every continuous signal, derive a faster rate for smooth signals and identify the persistent overshoot when a jump violates the assumptions.
Construct a convergent polynomial without differentiating the data
For continuous \(f\) on \([0,1]\), let \(K\) count successes in \(n\) independent Bernoulli trials of success probability \(x\). The expected sample \(B_nf(x)=E[f(K/n)]\) is a polynomial of degree at most \(n\). The weights sum to one and \(E[K/n]=x,\ {\rm Var}(K/n)=x(1-x)/n\). Let \(\omega_f(\delta)\) be the largest change in \(f\) between points at distance at most \(\delta\).
Given a target error, choose \(\delta\) using uniform continuity first, then \(n\) to control the second term. The bound holds simultaneously for every \(x\). For an \(L\)-Lipschitz signal, Cauchy–Schwarz improves the argument directly to \(\|B_nf-f\|_\infty\le L/(2\sqrt n)\). For \(f(x)=x^2\), taking the second moment gives the exact excess \(x(1-x)/n\). Existence of a uniformly good polynomial gives no guarantee that interpolating arbitrary samples will find it.
Relate interpolation error to best achievable error
For distinct nodes let \(I_n\) interpolate and \(\ell_j\) be the cardinal polynomials. Its operator norm in the maximum norm is \(\Lambda_n=\max_x\sum_j|\ell_j(x)|\). At a maximising point, data with the signs of the cardinal functions attain the bound and can be extended continuously between nodes. For any polynomial \(p\) of degree at most \(n\), \(I_np=p\), so subtraction gives
For Chebyshev extrema the angular representation \(x=\cos\theta\) makes the cardinal functions shifted trigonometric kernels. Their absolute contributions away from the nearest angular node are bounded by a constant times \(1/j\), using \(\sin u\ge 2u/\pi\) on \([0,\pi/2]\). The nearest term is bounded. Summing yields \(O(\log n)\) growth. At equally spaced nodes the barycentric weights are proportional to \((-1)^j{n\choose j}\), giving very large alternating interior weights near an endpoint as degree increases. To obtain an explicit lower bound, measure distance in grid spacings and evaluate at \(1/2\). Since \(\prod_{i=0}^n|1/2-i|/n!={2n\choose n}/(2\,4^n)\), the absolute value of the \(j\)th cardinal polynomial there is this factor times \({n\choose j}/|j-1/2|\). For \(j=\lfloor n/2\rfloor\), the central-binomial estimate gives growth at least proportional to \(2^n/n^2\). A single cardinal function is already enough to prove exponential growth of the norm. This explains why the same best error can coexist with very different interpolation errors.
Compare an analytic continuation, a corner and a jump
Put \(g(\theta)=f(\cos\theta)\). Chebyshev coefficients are cosine coefficients of an even periodic function. If the periodic \(g\) has \(m\) absolutely continuous derivatives and the next derivative is integrable, integration by parts \(m+1\) times bounds its coefficients by \(Ck^{-(m+1)}\). For \(m\ge1\), summing the tail gives \(O(n^{-m})\). Piecewise smooth functions can be treated by integrating each smooth interval and retaining internal jump terms. For \(|\cos\theta|\), continuity removes the first boundary term while the derivative jumps, giving coefficients of order \(k^{-2}\) and a tail of order \(1/n\). Analytic extension to an ellipse instead gives the geometric tail developed in the course's interpolation chapter.
At a jump of height \(J\), continuous approximants cannot have a uniform error below \(|J|/2\) on a domain containing both sides. For a periodic step of height 2, its sine series involves \((4/\pi)\sin((2j+1)x)/(2j+1)\). At \(x=z/(2N)\) the first \(N\) terms form a midpoint Riemann sum tending to \((2/\pi)\int_0^z\sin(t)/t\,dt\). Its first maximum, at \(z=\pi\), is about 1.179. The overshoot persists while its width shrinks. A mean-square error can still decrease.
How should a convergence plot treat the jump itself?
Report the maximum over the whole interval, a second maximum excluding a fixed physical neighbourhood of the jump and an integrated squared error. Sampling at a fixed small set of points can miss the narrowing peak entirely. Increase the sampling resolution with the polynomial degree.

Tutorial on changing the order of limits
Obtain an explicit degree requirement for a bounded slope
Work through the solution
For a target maximum error \(0.01\) and \(L=2\), the Lipschitz estimate guarantees \(n\ge10^4\). This is a sufficient degree. For the specific quadratic the exact worst error is \(1/(4n)\), requiring only \(n\ge25\).
Predict the effect of measurement error on both meshes
Work through the solution
Bounded nodal errors of size \(\epsilon\) perturb the interpolant by at most \(\Lambda_n\epsilon\). Even if the noiseless tail decreases geometrically, at fixed instrument accuracy the noise term eventually dominates. On an equally spaced mesh increasing the degree can make the prediction worse.
Trefethen · approximation, regularity and interpolation
Change parameters · What can smoothness buy at a fixed polynomial degree?
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.
Function approximation and numerical integration · 7. When should the denominator be fitted too?
Develop a minimax certificate for rational approximants, find the pole of a measured response and identify the obstruction that appears when a trial denominator vanishes inside the interval.
Count independently adjustable coefficients
Write \(r(x)=p_m(x)/q_n(x)\) on a compact real interval. Scaling numerator and denominator together leaves the response unchanged. Require a pole-free denominator of fixed sign and a normalisation, such as \(q(0)=1\) when admissible. For \(r,s\) of the same type,
The numerator has degree at most \(m+n\). If the error of a candidate takes alternating signs with magnitude \(E\) at \(m+n+2\) ordered points and never exceeds \(E\), any strictly better pole-free approximant would force \(m+n+1\) sign changes of the numerator. That is impossible unless the difference vanishes identically. This proves sufficiency. Common factors or unused degrees cause defects and can reduce the necessary alternation count. The certificate requires the global maximum between tested points to be checked.
Recompute the extreme points after changing the pole
For \(m=n=1\), \(q=1+cx\), impose \(p(x_i)=[f(x_i)-(-1)^i E](1+cx_i)\) at four proposed points. Products \(Ec\) make this nonlinear. One Remez-type iteration solves those four equations for the coefficients and \(E\), searches between the old points for extrema of \(f-r\), then exchanges points until magnitudes agree and the denominator retains its sign. Locating roots of \((f-r)'\), plus testing endpoints, is essential. A dense sample alone gives only a lower bound on the supremum.
For an explicit example approximate \(f(x)=1/(2-x)\) on \([-1,1]\). A linear best approximant must have the endpoint-error line as a starting shape. The endpoint secant is \(s(x)=2/3+x/3\). Convexity makes \(s-f\ge0\), maximised where \(1/(2-x)^2=1/3\), hence \(x=2-\sqrt3\). Set \(d=s(x)-f(x)=(4-2\sqrt3)/3\) there. Moving the line down by \(d/2\) produces three equal alternating errors and proves optimality for degree one. The type \((0,1)\) rational function \(p=1/2,\ q=1-x/2\) gives zero error. A comparison at equal parameter count has a physical interpretation when a material response genuinely has a nearby pole.
Why does matching a series at the origin give a different optimisation problem?
Padé chooses derivatives at one point. Uniform best approximation chooses the largest error over an interval. For a response with a small additional smooth background the Padé coefficients still reproduce the local series, but its largest positive and negative errors generally have unequal magnitudes. Use held-out values near the interval boundaries.

Tutorial on poles and certificates
Give an interval-wide error bound when the fitted pole is uncertain
Work through the solution
For \(f_a=1/(a-x)\) with \(a>1+\epsilon\) and \(|\Delta a|\le\epsilon\), subtraction gives \(|f_{a+\Delta a}-f_a|\le\epsilon/[(a-1)(a-1-\epsilon)]\). A tightly fitted pole near the endpoint can still create a large uncertainty in the response.
Construct a counterexample to using a few residuals as the certificate
Work through the solution
Samples at \(-1,0,1\) all avoid \(x=0.3\). The function \(\eta/(x-0.3)\) has arbitrarily small values at those samples when \(\eta\) is small, yet unbounded interior magnitude. Verify the denominator is nonzero over the entire interval before interpreting alternation at measured points.
Trefethen · rational approximation and minimax theory
Change parameters · When should the denominator be fitted too?
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.
Function approximation and numerical integration · 8. Measuring an area integral with finitely many samples
Build deterministic multidimensional rules from moments and geometry. Compare tensor products, symmetric triangle rules and sparse combinations at a fixed number of evaluations.
Which polynomials does a product rule integrate?
On a rectangle Fubini's theorem factors integrals of \(x^iy^j\). Applying a one-dimensional rule in each direction forms weights \(w_aw_b\) at pairs \((x_a,y_b)\). If each factor integrates through degree \(2n-1\), the tensor rule integrates every monomial with each exponent at most \(2n-1\), including some of total degree above that number. For \(d\) axes the price is \(n^d\) values. Unequal smoothness can justify different orders on different axes.
On the reference triangle \(x,y\ge0,\ x+y\le1\), integration of the inner monomial followed by the beta integral gives
Seek a symmetric three-node rule at permutations of barycentric coordinates \((a,b,b)\). Symmetry integrates affine functions once the weights each equal \(1/6\). Matching \(x^2\) gives \((a^2+2b^2)/6=1/12\) with \(a+2b=1\). One solution uses \(a=2/3,b=1/6\). The quadratic cross moment follows from barycentric symmetry and \((x+y+z)^2=1\). For a physical triangle multiply the reference weights by the absolute Jacobian determinant. For a curved mapping the determinant may itself vary across nodes.
Move the singularity into the Jacobian
Suppose a surface flux density on the same triangle is \(1/\sqrt{x+y}\). With \(s=x+y,\ v=y/(x+y)\), the map \(x=s(1-v),y=sv\) has determinant \(s\). Hence the total is \(\int_0^1\int_0^1 s^{1/2}\,dv\,ds=2/3\). Substituting \(s=u^2\) gives integrand \(2u^2\). Two Gauss nodes along \(u\) and one along \(v\) now suffice in exact arithmetic. A Cartesian mapping \(x=u,y=(1-u)v\) leaves an endpoint singularity even after multiplication by its Jacobian.
OneSimulation experiment · Integrate a singular field over a triangle
Vary the tensor order. Predict which transformed integrand is exactly integrated first.
Download the executable notebook · Python source
Adjust the experiment in the browser. Generalise the flux to \((x+y)^{-p}\), with \(0\le p<2\). Writing \(s=x+y\) gives \(\int_0^1s^{1-p}\,ds=1/(2-p)\). The squared radial map has transformed integrand \(2u^{3-2p}\). Change the exponent and quadrature order, then predict when a polynomial integrand permits exact Gauss integration. In particular, increasing \(p\) past \(3/2\) leaves an integrable singularity even in the radial coordinate. The browser constructs the Gauss nodes by Legendre root iteration; the notebook obtains the same rules from OneSimulation for the \(p=1/2\) reference case.
"""Integrate a corner singularity over the unit right triangle by two maps."""
import matplotlib.pyplot as plt
import numpy as np
from onesim.numerics.discretization.geometry.carriers.kernels.quadrature.rules.reference_quadrature import gauss_legendre
orders = [1, 2, 3, 4]
errors = [[], []]
for order in orders:
points, weights = np.asarray(gauss_legendre(order)).T
nodes, weights = (points+1)/2, weights/2
u, v = np.meshgrid(nodes, nodes, indexing="ij")
# First map x=u, y=(1-u)v. Second map x=u²(1-v), y=u²v.
values = [(1-u) / np.sqrt(u+(1-u)*v), 2*u**2 * np.ones_like(v)]
for sequence, integrand in zip(errors, values):
sequence.append(abs(weights @ integrand @ weights - 2/3))
print(f"Order {orders[-1]} errors: Cartesian map {errors[0][-1]:.6g}, radial map {errors[1][-1]:.3g}")
assert max(errors[1][1:]) < 1e-13
fig, ax = plt.subplots(figsize=(7, 4), layout="constrained")
for err, label in zip(errors, ["Cartesian map", "Radial map"]):
ax.semilogy(np.square(orders), np.maximum(err, 1e-16), "o-", label=label)
ax.set(xlabel="Number of function values", ylabel="Absolute error (plot floor 1e−16)")
ax.legend()
fig.savefig("numerics-triangle-cubature.png", dpi=170)
Output from the reference run
Order 4 errors: Cartesian map 0.00311717, radial map 1.11e-16

Buy mixed resolution only where it matters
Let \(Q_l\) be nested one-dimensional rules of growing order, \(Q_0=0,\Delta_l=Q_l-Q_{l-1}\). Telescoping the full tensor rule gives a sum of products of increments. In two dimensions retain terms with \(l_1+l_2\le q\), \(l_i\ge1\). This construction spends few evaluations at points fine in both directions. If mixed derivatives control the product increments, many omitted terms are small. A sharp oblique ridge can violate that premise. Refining only along individual axes then misses the ridge.
For \(q=3\), the combination is \(Q_2\otimes Q_1+Q_1\otimes Q_2-Q_1\otimes Q_1\). Take midpoint and Simpson as nested levels on \([0,1]\). Five distinct points replace the nine in the full tensor Simpson grid. A test on \(x^2y^2\) gives \(1/12+1/12-1/16=5/48\), compared with exact \(1/9\). The difference is exactly the mixed increment omitted from this level.
How can two deterministic estimates agree for the wrong reason?
A compact nonnegative bump placed between all sampled nodes returns zero on both grids. To certify an error, use an available derivative or interval bound on each region, or change the sampling geometry independently. An observed difference is an estimator whose reliability depends on resolving the integrand.
Tutorial on domains and evaluation budgets
Transport the triangle rule to vertices (0,0), (4,0), (1,2)
Work through the solution
The matrix mapping coordinate differences has columns \((4,0),(1,2)\) and determinant 8. The three weights are \(8/6\). Their sum is the area 4. Compute each physical node as the same barycentric combination of the physical vertices.
Decide which quadrature to buy for three dimensions
Work through the solution
With five levels of points per coordinate, the tensor rule costs \(5^3=125\). If the integrand is a sum \(g(x)+h(y)+k(z)\), product increments involving refinement in two directions vanish because differences annihilate constants. A sparse rule can recover the separate one-dimensional accuracy. A dependence on \(x+y+z\) generally reintroduces mixed terms.
Approximating a measured field
Reconstruct a potential from weighted modes. Compare orthogonality in a rectangle, cylinder and sphere, and determine which coefficients can be recovered from noisy measurements.
- Rectangular geometries, orthogonality and sources that drive individual modes
- Cylindrical geometry, coaxial boundaries and Bessel spectra
- Normalised spherical harmonics and the field of an arbitrary three-dimensional source
- Reconstructing a source from noisy voltage measurements
- Weighted least squares and residual diagnostics
- How model error masquerades as a fitted physical parameter
Sampling, propagation and unresolved scales
Apply quadrature and spectral approximation to a real aperture, a decaying field and a radiated-power measurement. Look for an observed convergence rate and explain any plateau.
- Diffraction from the near field to the focal plane
- What can a mesh measure about a point charge?
- Separate diffraction from a finite observation window
- When differentiating a measured dipole invents radiated power
- Verification, refinement and local error
- What a periodic grid does to a decaying Fourier mode
- Diffraction as a Fourier transform
- How a grating separates wavelengths
- Scattering from a central potential and what angular data can recover
- Action, angle and the slowing clock at a separatrix
- What a momentum eigenstate means in a finite experiment
- How a turning point supplies the missing semiclassical phase
- Measure gravity with a pendulum of finite amplitude
Applied study
Reconstruct a field from samples and estimate how interpolation changes its integral.
What lies between two measurements?
A probe records temperatures at equally spaced positions along a rod. To estimate the mean temperature, first decide what profile those samples represent. For neighbouring points \(x_j,x_{j+1}\) at distance \(h\), write \(x=x_j+sh\) with \(0\leq s\leq1\). The straight line matching both readings is
The weights are nonnegative and sum to one. This reproduces every affine function, keeps interpolated values between their neighbours, and amplifies bounded sample errors by at most a factor of one. A finer display grid can draw this line more densely. Recovering new curvature requires new source information.
Use curvature to predict the sign and size of error
For twice continuously differentiable \(f\), the interpolation remainder on one panel is \(f(x)-I_h f(x)=\tfrac12 f''(\xi)(x-x_j)(x-x_{j+1})\) for some \(\xi\) on that panel. The product is nonpositive and reaches magnitude \(h^2/4\) at the midpoint. Thus the maximum error is bounded by \(h^2\max|f''|/8\). For positive curvature the chord lies above the curve.
Integrating the chord gives \(h[f(x_j)+f(x_{j+1})]/2\), the trapezoidal rule. Integrating the bound with the quadratic factor retained gives a panel integral error at most \(h^3\max|f''|/12\). On a fixed interval of length \(L\) there are \(L/h\) panels, so the composite error is bounded by \(Lh^2\max|f''|/12\). The pointwise and total error both decrease quadratically, for different reasons.
Integrate a curved temperature profile
Use the exact profile \(T(x)=300+20(x/L)^2\) K with \(L=1\) m. Four equal panels have \(h=0.25\) m. On the first panel the endpoints are 300 and 301.25 K. Their interpolated midpoint is 300.625 K, while the exact midpoint is 300.3125 K. The overestimate of 0.3125 K is the same on every panel because the curvature is constant.

The exact integral is \(300+20/3=306.6667\) K·m on this unit-length rod. Here \(T''=40\) K/m² and the trapezoidal overestimate equals \(Lh^2 T''/12=0.20833\) K·m. Dividing the integral by length gives mean temperature. To obtain thermal energy above a reference temperature, additional material properties and cross-sectional area are needed.
Problem class
Choose the sensor spacing
For the quadratic rod, select the minimum number of equal intervals so the midpoint error never exceeds 0.05 K. How many measurements are needed including both endpoints?
Show the calculation
With \(N\) intervals on a metre, the bound is
Requiring \(5/N^2\leq0.05\) gives \(N\geq10\), hence 11 measurements. At constant curvature this bound is attained at the midpoints.
Infer an integral from two estimates
Four and eight panels give 306.875 and 306.71875 K·m. Assume \(Q_h=Q+c h^2\). Eliminate \(c\) and estimate \(Q\). Would adding sensors only to the display grid make this correction possible?
Show the calculation
Multiply \(Q_{h/2}=Q+c h^2/4\) by four and subtract \(Q_h\). This gives \(Q=(4Q_{h/2}-Q_h)/3=306.66667\) K·m. For the quadratic profile the error law is exact. Subdividing the same source chords on screen preserves their total area and supplies no second source approximation.
OneSimulation laboratory
Measure what interpolation does to a heat integral
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
Notation and assumptions
Read each defining equation with its assumptions and units, then follow the link to the argument that gives the equation its meaning.
Barycentric weight
Only relative weights enter the rational expression for the interpolating polynomial. At a node return the recorded value directly.
Derivation · Evaluating an interpolant without rebuilding its polynomial
Fourier alias
On n equally spaced periodic samples two distinct continuum frequencies can yield precisely the same observations. Interpolation cannot disambiguate them without more information.
Derivation · When a trapezoidal sum counts the wrong frequency perfectly
Interpolation condition
The polynomial matches the tabulated values at distinct nodes. Small nodal discrepancies do not guarantee a small error between nodes.
Monte Carlo standard error
Independent samples with finite variance give this ideal error scale. Importance weights and correlations can substantially alter the variance of the actual estimator.
Derivation · Where should a random quadrature spend its samples?
Quadrature degree
Exactness through degree d is an algebraic property. For a nonsmooth or poorly sampled integrand the observed rate can be much lower.
Richardson extrapolation
This cancels an assumed leading error proportional to h to power p. Several refinements can test whether that asymptotic regime is present.
Derivation · Deriving Romberg integration and recognising a broken error model
Further reading
Use the Chebyshev examples to connect coefficient decay and smoothness. Compare a function with an interior corner to one with a nearby complex singularity. Lloyd N. Trefethen · Approximation Theory and Approximation Practice
Chapters 5 and 9 give complementary local and global approximations. Compare those constructions on identical samples. Driscoll and Braun · Fundamentals of Numerical Computation




