Advertisement
CleverCode

Lagrange Polynomial

Jul 5th, 2020
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.90 KB | None | 0 0
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3.  
  4.  
  5. class LagrangePolynomial:
  6.  
  7.     def __init__(self, x, y):
  8.         self.k = len(x)
  9.         self.x = np.array(x)
  10.         self.y = np.array(y)
  11.  
  12.     def basis(self, x_, j):
  13.         b = [(x_ - self.x[m]) / (self.x[j] - self.x[m]) for m in range(self.k) if m != j]
  14.         return np.prod(b, axis=0) * self.y[j]
  15.  
  16.     def interpolate(self, x_):
  17.         b = [self.basis(x_, j) for j in range(self.k)]
  18.         return np.sum(b, axis=0)
  19.  
  20.  
  21. def main():
  22.     x = [-9, -4, -1, 7]
  23.     y = [5, 2, -2, 9]
  24.  
  25.     plt.scatter(x, y, c='k')
  26.  
  27.     lp = LagrangePolynomial(x, y)
  28.  
  29.     x_ = np.arange(-100, 100) / 10
  30.  
  31.     plt.plot(x_, lp.basis(x_, 0))
  32.     plt.plot(x_, lp.basis(x_, 1))
  33.     plt.plot(x_, lp.basis(x_, 2))
  34.     plt.plot(x_, lp.basis(x_, 3))
  35.     plt.plot(x_, lp.interpolate(x_), linestyle=':')
  36.  
  37.     plt.show()
  38.  
  39.  
  40. if __name__ == '__main__':
  41.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement