Lagrange Interpolation With Python

1 minute read

Lagrange Interpolation

Mathematical Background

This technique is useful for un-equspaced data points and if you’ve taken a course in Numerical Analysis you probably are familiar with this technique among other interpolation methods like the

  • Netwon’s Forward Difference Interpolating Polynomial and
  • Netwon’s Backward Difference Interpolating Polynomial

It allows us to find values of unseen data points based on existing data,value pairs

From the definition of gradient, we take three points \((x,f(x)), (x_{0},f(x_{0})) , (x_{1},f(x_{1}))\)

x \(x_{0}\) \(x_{1}\)
\(f(x)\) \(f(x_{0})\) \(f(x_{1})\)

To find the gradient of a function we use,

\[\frac{ \delta y}{ \delta x} = \frac{f(x) - f(x_{0})}{x - x_{0}} = \frac{f(x_{0}) - f(x_{1})}{x_{0} - x_{1}}\]

Let us solve for \(f(x)\).

Solution

By cross multiplication we have,

\[(f(x) - f(x_{0}))(x_{0} - x_{1}) = (f(x_{0}) - f(x_{1}))(x - x_{0})\]

Expanding the Multiplication on both sides,

\[x_{0}f(x) - x_{0}f(x_{0}) - x_{1}f(x) + x_{1}f(x_{0}) = xf(x_{0}) - xf(x_{1}) - x_{0}f(x_{0}) + x_{0}f(x_{1})\]

Removing the common term \(x_{0}f(x_{0})\) from both sides we have:

\[x_{0}f(x) - x_{1}f(x) + x_{1}f(x_{0}) = xf(x_{0}) - xf(x_{1}) + x_{0}f(x_{1})\]

Grouping terms of \(f(x)\) on one side we have:

\[x_{0}f(x) - x_{1}f(x) = xf(x_{0}) - xf(x_{1}) + x_{0}f(x_{1}) - x_{1}f(x_{0})\]

Reducing the equation to

\[(x_{0} - x_{1})f(x) = (x - x_{1})f(x_{0}) + (x_{0} - x)f(x_{1})\]

solving for \(f(x)\) by dividing both sides by \((x_{0} - x_{1})\) we obtain:

\(f(x) = \frac{(x - x_{1})f(x_{0}) + (x_{0} - x)f(x_{1})}{x_{0} - x_{1}}\) or

\[f(x) = \frac{x - x_{1}}{x_{0} - x_{1}}f(x_{0}) +\frac{x_{0} - x}{x_{0} - x_{1}}f(x_{1})\]

Example

Writing a Python Script to Solve this problem.

I wrote a program in python that takes \(x_{0},x_{1},x,f(x_{0}) and f(x_{1})\) values and returns the result, \(f(x)\) after performing lagrange interpolation using the data.

#!python
#lagrange.py x0, x1, f(x0), f(x1) X
from argparse import ArgumentParser

def foX(X,x0=0,x1=0,f_x0=0,f_x1=0):
    x0_x1=x0-x1
    x0_X=x0-X
    X_x1=X-x1
    f_x1=f_x1
    f_x0=f_x0
    f_X=( (x0_X*f_x1)/x0_x1 ) + ( (X_x1*f_x0)/x0_x1 )
    return f_X

if __name__=='__main__':
    parser=ArgumentParser()
    parser.add_argument('-x0',action='store',dest='x0',help="X0 value",type=float)
    parser.add_argument('-x1',action='store',dest='x1',help="X1 value",type=float)
    parser.add_argument('-f_x0',action='store',dest='f_x0',help="f_X0 value",type=float)
    parser.add_argument('-f_x1',action='store',dest='f_x1',help="f_X1 value",type=float)
    parser.add_argument('-X',action='store',dest='X',help="X value to interpolate",type=float)
    args=parser.parse_args()
    print("f(%f) is %f"%(args.X,foX(args.X,args.x0,args.x1,args.f_x0,args.f_x1)))

Categories: ,

Updated: