I need to calculate coefficients of polynomial using Lagrange interpolation polynomial, as my homework, I decide to do this in Javascript.
here is definition of Lagrange polynomial (L(x))

Lagrange basis polynomials are defined as follows

Calculate y value for specific X (W(x) function) is simple but I need to calculate coefficients of polynomial (array of [a0, a1, …, an]) I need to do this to n<=10 but it will be nice to have arbitrary n, then I can put that function into horner function and draw that polynomial.

I have function that calculate denominator in first equation
function denominator(i, points) {
var result = 1;
var x_i = points[i].x;
for (var j=points.length; j--;) {
if (i != j) {
result *= x_i - points[j].x;
}
}
return result;
}
and function that return y using horner method (I also have drawing function using canvas)
function horner(array, x_scale, y_scale) {
function recur(x, i, array) {
if (i == 0) {
return x*array[0];
} else {
return array[i] + x*recur(x, --i, array);
}
}
return function(x) {
return recur(x*x_scale, array.length-1, array)*y_scale;
};
}
anybody know algorithm to do this, or idea how to calculate those coefficients
Well, you can do it the naive way. Represent a polynomial by the array of its coefficients, the array
corresponding to
a_0 + a_1*X + ... + a_n*X^n. I’m no good with JavaScript, so pseudocode will have to do:Start with the constant polynomial
1/((x_1-x_0)* ... *(x_i-x_{i-1})*(x_i-x_{i+1})*...*(x_i-x_n))and multiply withX - x_kfor allk != i. So that gives the coefficients for Li, then you just multiply them with yi (you could do that by initialisingcoefficientstoy_i/denominator(i,points)if you pass the y-values as parameters) and add all the coefficients together finally.Calculating each Li is O(n²), so the total calculation is O(n³).
Update: In your jsFiddle, you had an error in the polynomial multiplication loop in addition to (the now corrected) mistake with the start index I made, it should be
Since you decrement
jwhen testing, it needs to start one higher.That doesn’t produce a correct interpolation yet, but it’s at least more sensible than before.
Also, in your
hornerfunction,you multiply the highest coefficient twice with
x, it should beinstead. Still no good result, though.
Update2: Final typo fixes, the following works: