python - python中线性插值的逻辑错误

标签 python interpolation bilinear-interpolation

我的线性插值有一些逻辑错误,它适用于某些情况,但不完全有效。

我尝试使用不同的方式来编写外推情况的逻辑。

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  

插值([1, 3, 5], [1, 9, 25], 5.0) 我预计输出是 25,但实际输出是 17.0。

最佳答案

我认为您正在寻找这样的东西:

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))

输出:

25

注意,我将 breaks 更改为 continues

关于python - python中线性插值的逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56015342/

相关文章:

c++ - 多重双线性插值的更快方法?

Python:MySQLdb 和 "Library not loaded: libmysqlclient.16.dylib"

数学 - 映射数字

plot - gnuplot - 平滑插值 x=f(y)

python - 如何使用 Python 插入 3D 曲面图(2D 数组)的缺失值(未定义区域)?

algorithm - 填充二维数组的空隙

python - 在Python中查找与某个字符串相关的所有元组

python - 在 Django Rest Framework 中使用 Tokenauthentication 进行身份验证时,last_login 字段未更新

python - 如何使用 matplotlib 在子图中调整图形大小