Interpolation and approximation
The polynomial through a set of points, in Newton's and Lagrange's forms with exact divided differences; the error formula beside the true error; Chebyshev nodes and the Runge phenomenon; natural cubic splines and least-squares polynomials, all with exact rational coefficients.
const p = interpolate([[0, 1], [1, 3], [2, 2]]);
p.polynomial; // "-3/2*x^2 + 7/2*x + 1"
p.newton; // "1 + 2*x - 3/2*x*(x - 1)"
p.dividedDifferences; // [[1, 3, 2], [2, -1], [-3/2]] exact
p.at("1/2"); // 19/8
const q = interpolate("sin(x)", { nodes: equallySpaced(0, 1, 4) });
q.maxError([0, 1]); // { value, attained, at, textbook }
Divided differences
Through points with distinct there is exactly one polynomial of degree at most . Newton's form builds it one node at a time:
The table of divided differences is computed in exact rational arithmetic, so for data given as rationals the polynomial is the true one, with no rounding. Lagrange's form writes the same polynomial as , where is 1 at and 0 at the other nodes.
The error formula
If has continuous derivatives, then for each there is a with
maxError reports the true maximum of on an interval, bracketed between a value attained and a proven upper bound, and beside it the bound the formula gives, , with both maxima enclosed.
Runge's example and Chebyshev nodes
More nodes need not mean a better fit. For on with equally spaced nodes the error near the ends grows without bound as the degree rises. The product is the part of the error formula that the choice of nodes controls, and it is smallest in maximum when the nodes are the Chebyshev points
which crowd towards the ends. chebyshevNodes(a, b, n) returns them rounded to nearby rationals.
Splines and least squares
A natural cubic spline is a cubic on each interval between nodes, with two continuous derivatives across the nodes and zero second derivative at the two ends. The second derivatives at the nodes solve a tridiagonal system, here exactly. A least-squares polynomial of degree minimises ; its coefficients solve the normal equations , again exactly, and the residual is returned as an exact rational.
| call | returns |
|---|---|
| interpolate(points) or interpolate(f, { nodes }) | { nodes, values, dividedDifferences, newton, lagrange, polynomial, coefficients, at(x), error(x), maxError([a, b]) } |
| equallySpaced(a, b, n), chebyshevNodes(a, b, n) | arrays of Rationals |
| spline(points) | { pieces: [{ from, to, coefficients, polynomial }], moments, at(x) } |
| leastSquares(points, degree = 1) | { coefficients, polynomial, residual, at(x) } |
@ratmath/analytic and Core's R, Rational, RationalInterval in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.