在 Python 中不指定索引的插值

Interpolation without specifying indices in Python

我有两个长度相同的数组,比如数组 x 和数组 y。我想找到 x=0.56 对应的 y 的值。这不是数组 x 中存在的值。 我希望 python 自己找到大于 0.56(及其对应的 y 值)的最接近值和小于 0.56(及其对应的 y 值)的最接近值。然后简单插值求x 0.56时y的值。

我自己找到两个x值和对应的y值的索引并输入到Python中就很容易了(见下面的代码)。 但是python有什么方法可以自己找到索引吗?

#interpolation:
def effective_height(h1,h2,g1,g2):
    return (h1 + (((0.56-g1)/(g2-g1))*(h2-h1)))

eff_alt1 = effective_height(x[12],x[13],y[12],y[13])

在这段代码中,我必须找到索引 [12] 和 [13] 对应于最接近 0.56 的较小值和最接近 0.56 的较大值。

Now I am looking for a similar technique where I would just tell python to interpolate between the two values of x for x=0.56 and print the corresponding value of y when x=0.56.

我看过 scipy 的插值,但我认为它对这种情况没有帮助,尽管进一步说明我如何在我的情况下使用它也会有所帮助。

Numpy interp 做你想做的事吗?:

import numpy as np
x = [0,1,2]
y = [2,3,4]
np.interp(0.56, x, y)
Out[81]: 2.56

给定您的两个数组,xy,您可以使用 SciPy.

执行类似以下操作
from scipy.interpolate import InterpolatedUnivariateSpline

spline = InterpolatedUnivariateSpline(x, y, k=5)
spline(0.56)

关键字k必须在1到5之间,并且controls the degree of the spline.

示例:

>>> x = range(10)
>>> y = range(0, 100, 10)
>>> spline = InterpolatedUnivariateSpline(x, y, k=5)
>>> spline(0.56)
array(5.6000000000000017)