Instantly share code, notes, and snippets.

# komasaru/interpolate_lagrange.py

Last active June 19, 2020 18:52
Show Gist options
• Save komasaru/aaca82968cf0b42c7d9aa3a90f17be62 to your computer and use it in GitHub Desktop.
Python script to interpolate with Lagrange method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 #! /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 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.