I learned about Lagrange interpolation in a university class, so I implemented it in Python.
Function interpolation is to derive a concatenated function that connects them from the points obtained discretely.
[Discrete]
【Continuous】
When the values of xj and f (xj) are set as known data points for j = 0,1,2… n
l_j(x) = \frac{(x-x_0)(x-x_1)…(x-x_{j-1})(x-x_{j+1})…(x-x_n)}{(x_j-x_0)(x_j-x_1)…(x_j-x_{j-1})(x_j-x_{j+1})…(x_j-x_n)}\\
P_n(x) = \sum_{j=0}^{n}f(x_j)l_j(x)
It will be like that. The important point is to skip the jth when finding lj (x). (Because it will be 0)
It will be as follows.
Lagrange.py
import numpy as np
import matplotlib.pyplot as plt
def lagurange(x,xp,fx):
results = [];
for l in range(len(x)):
if(x[l] in xp):
results.append(fx[np.where(xp==x[l])])
else:
result=0
for j in range(len(xp)):
lag = lx(x[l],j,xp)
result += fx[j]*lag
results.append(result)
return results
def lx(x,j,xp):
numerator,denominator = 1,1
for i in range(len(xp)):
if(i!=j):
numerator *= x-xp[i]
denominator *= xp[j]-xp[i]
return numerator/denominator
def main():
xp = np.arange(-10,10,3)
fx = xp**3
x = np.floor(np.arange(-10,10,0.1)*10)/10
y = lagurange(x,xp,fx)
plt.plot(x,y)
plt.plot(xp,fx,"o")
plt.show()
if __name__ == '__main__':
main()
I think there is a more efficient way of writing because I implemented it as it is without thinking about anything primitively. In this program, x of the function y = x ^ 3 is known as data in 3 increments, and Lagrange interpolation is performed in the range of x = -10 to 10 in 0.1 increments.
Known data points
After Lagrange interpolation
You have a solid approximation of y = x ^ 3.
Recommended Posts