Lagrange interpolation in Python

lagrange polynomial interpolation code python
2d lagrange interpolation python
barycentric lagrange interpolation python
newton interpolation python
lagrange interpolation algorithm
lagrange interpolation matlab
lagrange interpolation calculator
lagrange interpolation curve

I want to interpolate a polynomial with the Lagrange method, but this code doesn't work:

def interpolate(x_values, y_values):
    def _basis(j):
        p = [(x - x_values[m])/(x_values[j] - x_values[m]) for m in xrange(k + 1) if m != j]
        return reduce(operator.mul, p)

    assert len(x_values) != 0 and (len(x_values) == len(y_values)), 'x and y cannot be empty and must have the same length'

    k = len(x_values)
    return sum(_basis(j) for j in xrange(k))

I followed Wikipedia, but when I run it I receive an IndexError at line 3!

Thanks

Check the indices, Wikipedia says "k+1 data points", but you're setting k = len(x_values) where it should be k = len(x_values) - 1 if you followed the formula exactly.

Lagrange Interpolation Method: Algorithm, Computation and Plot , This tutorial explains the Lagrangian polynomial form of the interpolation function, the Duration: 18:28 Posted: Feb 12, 2020 Lagrange interpolation in python. GitHub Gist: instantly share code, notes, and snippets.

Try

def interpolate(x, x_values, y_values):
    def _basis(j):
        p = [(x - x_values[m])/(x_values[j] - x_values[m]) for m in xrange(k) if m != j]
        return reduce(operator.mul, p)
    assert len(x_values) != 0 and (len(x_values) == len(y_values)), 'x and y cannot be empty and must have the same length'
    k = len(x_values)
    return sum(_basis(j)*y_values[j] for j in xrange(k))

You can confirm it as follows:

>>> interpolate(1,[1,2,4],[1,0,2])
1.0
>>> interpolate(2,[1,2,4],[1,0,2])
0.0
>>> interpolate(4,[1,2,4],[1,0,2])
2.0
>>> interpolate(3,[1,2,4],[1,0,2])
0.33333333333333331

So the result is the interpolated value based on the polynomial that goes through the points given. In this case, the 3 points define a parabola and the first 3 tests show that the stated y_value is returned for the given x_value.

Lagrange interpolation in Python, Check the indices, Wikipedia says "k+1 data points", but you're setting k = len(​x_values) where it should be k = len(x_values) - 1 if you followed  Interpolation with python functions ¶. The interpolant polynomial can be computed with numpy function polyfit if we choose as polynomial degree the number of the nodes minus one. The output is the coefficients of the polynomial, from an to a0.

I'm almost a decade late to the party, but I found this searching for a simple implementation of Lagrange interpolation. @smichr's answer is great, but the Python is a little outdated, and I also wanted something that would work nicely with np.ndarrays so I could do easy plotting. Maybe others will find this useful:

import numpy as np
import matplotlib.pyplot as plt


class LagrangePoly:

    def __init__(self, X, Y):
        self.n = len(X)
        self.X = np.array(X)
        self.Y = np.array(Y)

    def basis(self, x, j):
        b = [(x - self.X[m]) / (self.X[j] - self.X[m])
             for m in range(self.n) if m != j]
        return np.prod(b, axis=0) * self.Y[j]

    def interpolate(self, x):
        b = [self.basis(x, j) for j in range(self.n)]
        return np.sum(b, axis=0)


X  = [-9, -4, -1, 7]
Y  = [5, 2, -2, 9]

plt.scatter(X, Y, c='k')

lp = LagrangePoly(X, Y)

xx = np.arange(-100, 100) / 10

plt.plot(xx, lp.basis(xx, 0))
plt.plot(xx, lp.basis(xx, 1))
plt.plot(xx, lp.basis(xx, 2))
plt.plot(xx, lp.basis(xx, 3))
plt.plot(xx, lp.interpolate(xx), linestyle=':')
plt.show()

Lagrange interpolation in python · GitHub, import numpy as np. import matplotlib.pyplot as plt. import sys. def main():. if len(​sys.argv) == 1 or "-h" in sys.argv or "--help" in sys.argv: print "python lagrange.py​  Lagrange Interpolation is the sum of the functional value at a point times its respective basis polynomial (here denoted as ): Where the basis polynomial format is as follows: is constructed similarly: In both, we see that the numerator skips for the basis as this would zero every basis vector.

[PDF] Unit 5: Polynomial Interpolation, 5.8 Lagrange Polynomials in Python def lagrange(x,i,xm): """. Evaluates the i-th Lagrange polynomial at x based on grid data xm. """ n=len(xm)-1 y=1. In this tutorial, the theory and MATLAB programming steps of Lagrange's interpolation method are explained. *** For a full course of Numerical Methods in Python, visit: https://www.udemy.com

Lagrange's Interpolation, What's Difference? Quizzes expand_more. C · C++ · Java · Python · Data Structures · Algorithms · Operating Systems · DBMS · Compiler Design  The Lagrange’s Interpolation formula: If, y = f(x) takes the values y0, y1, … , yn corresponding to x = x0, x1 , … , xn then, This method is preferred over its counterparts like Newton’s method because it is applicable even for unequally spaced values of x.

W8V5 Python:Lagrange Interpolation, Interested in learning how to solve partial differential equations with numerical methods and how to turn them into python codes? This course provides you with​  Lagrange or Newton are examples of polynomial interpolation. Just to mention and to introduce different interpolation problems approaches in scipy, let's see the Lagrange interpolation: f = interpolate.lagrange(x, y) yn = f(xn) The barycentric interpolation uses Lagrange polynomials. We can calculate the interpolated values directly with the interpolation functions:

Comments
  • I would be grateful if the downvoters would explain the downvote...
  • Thank you! Now I check this and I tell you the result.
  • Ok, and why if I do: interpolate([1, 2, 3], [1, 4, 9]) it returns -0.5x^2 + 1.5x ? Take a look at this: i.imgur.com/MkATz.gif
  • @rubik: Sorry, but I can't help you with such a specific problem without knowing the interpolation algorithm (and I won't read up on it). Check your logic again or search for an existing implementation. If you post more code on how you apply the interpolation (e.g. the definition/initial value of x is missing in your question), then somebody might be able to help you further.
  • I'm using pypol (pypol.altervista.org) and x is monomial(x=1) (pypol.altervista.org/functions.html#pypol.monomial)
  • Thank you! A bit late but I'll try that! :)
  • Can't believe that almost a decade has passed! Thanks for your contribution.