Piecewise-Polynomial Approximation
We begin by considering the approximation of continuous function by piece-wise linear functions.
A piece-wise linear function is a function that has a finite set of points where it is not linear, and is linear between any two adjacent pairs of finite points. More symbolically, a piece-wise linear function , where is a real number interval and is a field, generally the real or complex numbers in most applications, is a function such that there exists a set of points with the property: for any and such that , is linear on the interval , ie, there exists elements in and such that on the interval .
Theorem 1.
Let be a piece-wise linear function on the real interval with points of non-linearity .
Then for any , for all , has value
.
Proof.
To prove this, we take our input and find the borders of the interval which contain it. Because is linear between these two points, it must be the line that passes between the points and . The value of a point on this line is
.
∎
A piece-wise linear function with points of non-linearity has a simple representation as the set of values of the function at the points of non-linearity. The values give the values of the function at points where the derivative of the function is not a constant number. These values uniquely define the function.
Given these values , we can write a simple formula for the value of the function, which we can then implement in JavaScript.
function approximate(xvals, fvals, xin) {
if (xvals.length != fvals.length) {
console.error("mismatched array lengths");
return;
}
var { left, right } = findIndexes(xvals, xin);
var fxi = fvals[left],
fxj = fvals[right];
var xi = xvals[left],
xj = xvals[right];
return (xin * (fxj - fxi) + (fxi * xj - fxj * xi)) / (xj - xi);
}
function findIndexes(xvals, xin) {
var i = 0;
while (i < xvals.length) {
if (xvals[i] <= xin && xvals[i + 1] >= xin) {
return { left: i, right: i + 1 };
}
i++;
}
throw new Error("could not find indexes");
}
Below is an implementation of the preceding code.
Input the x values of the points of non-linearity in
the “x values” field, and the values of the function to estimate
f in the “f values” field, using the format
[ x1, x2, x3 ], when x1,
x2 and x3 represent any three 64-bit
integers.
Enter the input value of the variable x you’d like to
approximate the value of f(x) for, click
“approximate” button, and the approximate value of
f(x) should appear below the input fields and button,
in the part of the page where is currently written "The approximate value of f(x) will display here."