如何实现线性插值? [英] How to implement linear interpolation?
问题描述
说我得到的数据如下:
x = [1, 2.5, 3.4, 5.8, 6]
y = [2, 4, 5.8, 4.3, 4]
我想设计一个函数,该函数将在1
和2.5
之间,在2.5
到3.4
之间进行线性插值,依此类推,等等.
I want to design a function that will interpolate linearly between 1
and 2.5
, 2.5
to 3.4
, and so on using Python.
我已经尝试浏览此Python教程,但是我仍然无法理解
I have tried looking through this Python tutorial, but I am still unable to get my head around it.
推荐答案
据我了解您的问题,您想编写一些函数y = interpolate(x_values, y_values, x)
,该函数将在某些x
上为您提供y
值吗?然后,基本思路如下:
As I understand your question, you want to write some function y = interpolate(x_values, y_values, x)
, which will give you the y
value at some x
? The basic idea then follows these steps:
- 在
x_values
中查找值的索引,这些值定义了包含x
的间隔.例如,对于带有示例列表的x=3
,包含间隔将为[x1,x2]=[2.5,3.4]
,索引将为i1=1
,i2=2
- 通过
(y_values[i2]-y_values[i1])/(x_values[i2]-x_values[i1])
(即dy/dx
)计算该间隔的斜率. -
x
处的值现在是x1
处的值加上斜率乘以距x1
处的距离.
- Find the indices of the values in
x_values
which define an interval containingx
. For instance, forx=3
with your example lists, the containing interval would be[x1,x2]=[2.5,3.4]
, and the indices would bei1=1
,i2=2
- Calculate the slope on this interval by
(y_values[i2]-y_values[i1])/(x_values[i2]-x_values[i1])
(iedy/dx
). - The value at
x
is now the value atx1
plus the slope multiplied by the distance fromx1
.
您还需要确定如果x
在x_values
的间隔之外,会发生什么情况,这是一个错误,或者您可以插值向后",假设斜率与第一个/最后一个间隔相同.
You will additionally need to decide what happens if x
is outside the interval of x_values
, either it's an error, or you could interpolate "backwards", assuming the slope is the same as the first/last interval.
有此帮助吗?还是您需要更具体的建议?
Did this help, or did you need more specific advice?
这篇关于如何实现线性插值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!