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.
Here is some python code that generates a numpy.polynomial
from your set of points:
import numpy as np
from numpy.polynomial import Polynomial
import matplotlib.pyplot as plt
X = np.array([0, 1, 1.5, 2, 3])
Y = np.array([2, 8, 12, 10, 20])
n = len(X)
poly = Polynomial(np.zeros(n))
for j in range(n):
k = [k for k in range(n) if k != j]
roots = -1 * X[k]
sub_poly = Polynomial.fromroots(X[k])
scale = Y[j] / np.prod(X[j] - X[k])
sub_poly.coef *= scale
poly.coef += sub_poly.coef
You can then plot it via:
plt.scatter(X, Y)
Xinterp = np.linspace(min(X), max(X), 100)
plt.plot(Xinterp, poly(Xinterp))
plt.show()
Or to find a specific value:
print(poly(0.5))
Please see here for more information: https://learn.64bitdragon.com/articles/computer-science/numerical-analysis/lagrange-interpolation
Full disclosure: I'm the author of this article.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.