Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python script to interpolate with Lagrange method.
#! /usr/local/bin/python3.6
"""
Interpolation with Lagrange method
"""
import sys
import traceback
class InterpolateLagrange:
X = [0.0, 2.0, 3.0, 5.0, 8.0]
Y = [0.8, 3.2, 2.8, 4.5, 1.9]
def __init__(self):
self.n = len(self.X)
def compute(self):
""" Computation of interpolation with Lagrange method """
try:
print(" x y")
for a in range(int(self.X[-1]) * 2 + 1):
t = 0.5 * a
print("{:7.2f}{:7.2f}".format(t, self.__interpolate(t)))
except Exception as e:
raise
def __interpolate(self, t):
""" Interpoalation with Lagrange method
:param float t
"""
try:
s = 0.0
for i in range(0, self.n):
p = self.Y[i]
for j in range(0, self.n):
if i != j:
p *= (t - self.X[j]) / (self.X[i] - self.X[j])
s += p
return s
except Exception as e:
raise
if __name__ == '__main__':
try:
obj = InterpolateLagrange()
obj.compute()
except Exception as e:
traceback.print_exc()
sys.exit(1)
@louis1001
Copy link

louis1001 commented Jun 19, 2020

I made a few changes to this, so that it works as a function accepting the values as parameters.

def interpolate(t, xs, ys):
    s = 0.0
    n = len(xs)
    for i in range(n):
        p = ys[i]
        for j in range(n):
            if i != j:
                p *= (t - xs[j]) / (xs[i] - xs[j])
        s += p
    return s

def compute(xs, ys):
    for a in range(int(xs[-1]) * 2 + 1):
        t = 0.5 * a
        print("{:7.2f}{:7.2f}".format(t, interpolate(t, xs, ys)))

X = [0.0, 2.0, 3.0, 5.0, 8.0]
Y = [0.8, 3.2, 2.8, 4.5, 1.9]

compute(X, Y)

I needed this version for some homework. I know you have your reasons to do it with classes.
This was helpful. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment