Lagrange Interpolation in Python: The resulting mathematical formula

I am trying to use Lagrange interpolation for multiple points. As a result, I need a mathematical formula, for example:

Lx=[1,2,3],
Ly=[1,4,9],
result = x^2 

Instead i get "-4.0*X*(-0.5*X - 1.0)*(-0.2*X + 0.2)*(-0.142857142857143*X +..."

When I put, for example, 5 instead of X (line 12), I get "25", the correct answer. Can anybody help me?

import sympy 
def Lagrange (Lx, Ly):
    X=sympy.symbols('X')
    if  len(Lx)!= len(Ly):
        print "ERROR"
        return 1
    y=float(0.0)
    for k in range ( len(Lx) ):
        t=float(1.0)
        for j in range ( len(Lx) ):
            if j != k:
                t=t* ( (X-Lx[j]) / float(Lx[k]-Lx[j]) ) # when I put number, OK
        y+= t*Ly[k]
    return y

Lx=[-4,-2,0,1,3]
Ly=[16,4,0,1,9]
print Lagrange(Lx,Ly)
+4
source share
1 answer

This is probably due to rounding with floating point. Simplification gives:

In [10]: sympy.simplify(Lagrange(Lx,Ly))
Out[10]: X*(1.85037170770859e-17*X**2 + 1.0*X - 1.11022302462516e-16)

This is basically X**2. Try to get rid of these butts float:

def Lagrange (Lx, Ly):
    X=sympy.symbols('X')
    if  len(Lx)!= len(Ly):
        print "ERROR"
        return 1
    y=0
    for k in range ( len(Lx) ):
        t=1
        for j in range ( len(Lx) ):
            if j != k:
                t=t* ( (X-Lx[j]) /(Lx[k]-Lx[j]) )
        y+= t*Ly[k]
    return y

Gives me:

In [30]: Lx=[-4,-2,0,1,3]
In [31]: Ly=[16,4,0,1,9.]
In [32]: print Lagrange(Lx,Ly)
Out[32]: 1.0*X**2
+2
source

Source: https://habr.com/ru/post/1569719/


All Articles