Search code examples
pythoninterpolationbilinear-interpolation

logical error in Linear interpolation in python


My linear interpolation has some logical error, it works for certain cases but not completely working.

I have tried to use different way to write the logic for the cases of extrapolation.

def interpolate(x, y, x_test):
    for i in range(len(x)):
        if x[i] > x_test:   #extrapolated condition: when the largest value of
            x_below = i - 1 #list x is greater than x_test 
            x_above = i 
            y_below = i - 1
            y_above = i
            break
        elif x[i] < x_test: #extrapolated condition: when the largest value of 
            x_below = i + 1 #list x is greater than x_test 
            x_above = i 
            y_below = i + 1
            y_above = i
            break                
        else:             #interpolated condition: when x_test lies between  
            return y[i]    #two sample points.

    #a = (yabove - ybelow) / (xabove - xbelow)         
    a = (y[y_above] - y[y_below]) / (x[x_above] - x[x_below])  
    #b = ybelow - a * xbelow
    b = y[y_below] - a * x[x_below]
    #y’ = a * x’ + b
    return a * x_test + b  

interpolate([1, 3, 5], [1, 9, 25], 5.0) I expect the output is 25, but the actual output is 17.0.


Solution

  • I think you are looking for something like this:

    def interpolate(x, y, x_test):
        for i in range(len(x)):
            if x[i] > x_test:   #extrapolated condition: when the largest value of
                x_below = i - 1 #list x is greater than x_test
                x_above = i
                y_below = i - 1
                y_above = i
                continue # <---- I changed break to continue
            elif x[i] < x_test: #extrapolated condition: when the largest value of
                x_below = i + 1 #list x is greater than x_test
                x_above = i
                y_below = i + 1
                y_above = i
                continue # <---- I changed break to continue
            else:             #interpolated condition: when x_test lies between
                return y[i]    #two sample points.
    
        #a = (yabove - ybelow) / (xabove - xbelow)
        a = (y[y_above] - y[y_below]) / (x[x_above] - x[x_below])
        #b = ybelow - a * xbelow
        b = y[y_below] - a * x[x_below]
        #y’ = a * x’ + b
        return (a * x_test + b)
    
    print(interpolate([1, 3, 5], [1, 9, 25], 5.0))
    

    Output:

    25
    

    Notice, I changed the breaks to continues.