Skip to content
Advertisement

How to calculate coefficients of polynomial using Lagrange interpolation

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))

enter image description here

Lagrange basis polynomials are defined as follows

enter image description here

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.

enter image description here

I have function that calculate denominator in first equation

JavaScript

and function that return y using horner method (I also have drawing function using canvas)

JavaScript

anybody know algorithm to do this, or idea how to calculate those coefficients

Advertisement

Answer

Well, you can do it the naive way. Represent a polynomial by the array of its coefficients, the array

JavaScript

corresponding to a_0 + a_1*X + ... + a_n*X^n. I’m no good with JavaScript, so pseudocode will have to do:

JavaScript

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 with X - x_k for all k != i. So that gives the coefficients for Li, then you just multiply them with yi (you could do that by initialising coefficients to y_i/denominator(i,points) if you pass the y-values as parameters) and add all the coefficients together finally.

JavaScript

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

JavaScript

Since you decrement j when 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 horner function,

JavaScript

you multiply the highest coefficient twice with x, it should be

JavaScript

instead. Still no good result, though.

Update2: Final typo fixes, the following works:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement