Lagrange Interpolation Implementation In Python
Lagrange InterpolationPermalink
Mathematical BackgroundPermalink
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)),(x0,f(x0)),(x1,f(x1))(x,f(x)),(x0,f(x0)),(x1,f(x1))
x | x0x0 | x1x1 |
---|---|---|
f(x)f(x) | f(x0)f(x0) | f(x1)f(x1) |
To find the gradient of a function we use,
δyδx=f(x)−f(x0)x−x0=f(x0)−f(x1)x0−x1δyδx=f(x)−f(x0)x−x0=f(x0)−f(x1)x0−x1Let us solve for f(x)f(x).
SolutionPermalink
By cross multiplication we have,
(f(x)−f(x0))(x0−x1)=(f(x0)−f(x1))(x−x0)(f(x)−f(x0))(x0−x1)=(f(x0)−f(x1))(x−x0)Expanding the Multiplication on both sides,
x0f(x)−x0f(x0)−x1f(x)+x1f(x0)=xf(x0)−xf(x1)−x0f(x0)+x0f(x1)x0f(x)−x0f(x0)−x1f(x)+x1f(x0)=xf(x0)−xf(x1)−x0f(x0)+x0f(x1)Removing the common term x0f(x0)x0f(x0) from both sides we have:
x0f(x)−x1f(x)+x1f(x0)=xf(x0)−xf(x1)+x0f(x1)x0f(x)−x1f(x)+x1f(x0)=xf(x0)−xf(x1)+x0f(x1)Grouping terms of f(x)f(x) on one side we have:
x0f(x)−x1f(x)=xf(x0)−xf(x1)+x0f(x1)−x1f(x0)x0f(x)−x1f(x)=xf(x0)−xf(x1)+x0f(x1)−x1f(x0)Reducing the equation to
(x0−x1)f(x)=(x−x1)f(x0)+(x0−x)f(x1)(x0−x1)f(x)=(x−x1)f(x0)+(x0−x)f(x1)solving for f(x)f(x) by dividing both sides by (x0−x1)(x0−x1) we obtain:
f(x)=(x−x1)f(x0)+(x0−x)f(x1)x0−x1f(x)=(x−x1)f(x0)+(x0−x)f(x1)x0−x1 or
f(x)=x−x1x0−x1f(x0)+x0−xx0−x1f(x1)f(x)=x−x1x0−x1f(x0)+x0−xx0−x1f(x1)ExamplePermalink
Writing a Python Script to Solve this problem.Permalink
I wrote a program in python that takes x0,x1,x,f(x0)andf(x1)x0,x1,x,f(x0)andf(x1) values and returns the result, f(x)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)))