I was asked to use Lagrange Interpolation to draw a line that pass through several dots on a graph (scipy.interpolate.lagrange banned).
But it doesn't seem that my code can give the correct result. To be frank, I don't even know which part of it is wrong.
And if I was asked to find the value of a specific point on the line, how should I adjust the code to do so?
The first image is the expected output. The second one is the output from my code.
Can someone please tell me how to correct it?
Source code
import numpy as np
import matplotlib.pyplot as plt
m = 4
X = np.array([0, 1, 1.5, 2, 3])
Y = np.array([2, 8, 12, 10, 20])
def p(x):
px = 0;
for j in range(m+1):
Lmj = 1
for k in range(m+1):
if k != j:
Lmj *= (x - X[k])/(X[j] - X[k])
px += Y[j] * Lmj;
return px
plt.scatter(X, Y)
Xinterp = np.linspace(min(X), max(X), 100)
plt.plot(Xinterp, p(Xinterp))
plt.show()
Also, is that plt.show() line necessary? From my lecturer's notes, the code don't have this line and still can display a graph. But in my copied version of the source code, I need to add this line to show the graph.
Thank you very much for noticing this problem.