In numerical analysis, Lagrange polynomials are used for polynomial interpolation. For a given set of points (xj, yj) with no two xj values equal, the Lagrange polynomial is the polynomial of lowest degree that assumes at each value xj the corresponding value xj, so that the functions coincide at each point.
Given a set of k + 1 data points (x0, y0), …, (xj, yj), …, (xk, yk) where no two xj are the same, the interpolation polynomial in the Lagrange form is a linear combination
where 0 ≤ j ≤ k. Note how, given the initial assumption that no two xj are the same, xj − xm ≠ 0, so this expression is always well-defined. The reason pairs xi = xj with yi ≠ yj are not allowed is that no interpolation function L such that yi = L(xi) would exist; a function can only get one value for each argumetn xi. On the other hand, if also yi = yj, then those two points would actually be one single point.
For all i ≠ j, ℓ(x) includes the term (x − xi) in the numerator, so the whole pruduct will be zero at x = xi:
On the other hand,
In other words, all basis polynomials are zero at x = xi, except ℓi(x), for which it holds that ℓi(xi) = 1, because it lacks the (x − xi) term.
It follows that ℓi(xi) = yi, so at each point xi, L(xi) = yi + 0 + 0 + … + 0 = yi, showing that L interpolates the function exactly.
The function
Imagine that we have following points and we want to build a Lagrange polynomial with this points:
X | Y |
---|---|
2.0 | 10.0 |
3.0 | 15.0 |
5.0 | 25.0 |
8.0 | 40.0 |
12.0 | 60.0 |
Then the code will look like this:
// example_lagrange_polynomial.cpp
#include <iostream>
#include "../src/numerary.hpp" // Numerary library
using namespace std;
using namespace numerary;
/* The main function */
int main() {
const int N = 5;
double *X = new double[N], *Y = new double[N];
double y, x;
// Points to interpolate
X[0] = 2.0; Y[0] = 10.0;
X[1] = 3.0; Y[1] = 15.0;
X[2] = 5.0; Y[2] = 25.0;
X[3] = 8.0; Y[3] = 40.0;
X[4] = 12.0; Y[4] = 60.0;
// Point where we want to get value of Lagrange Polynomial
x = 7.0;
y = Numerary::lagrange_polynomial(X, Y, x, N);
cout << "y(" << x << ") = " << y << endl;
delete[] X;
delete[] Y;
return 0;
}