如何实现线性插值? [英] How to implement linear interpolation?

查看:123
本文介绍了如何实现线性插值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我得到的数据如下:

x = [1, 2.5, 3.4, 5.8, 6]
y = [2, 4, 5.8, 4.3, 4]

我想设计一个函数,该函数将在12.5之间,在2.53.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:

  1. x_values中查找值的索引,这些值定义了包含x的间隔.例如,对于带有示例列表的x=3,包含间隔将为[x1,x2]=[2.5,3.4],索引将为i1=1i2=2
  2. 通过(y_values[i2]-y_values[i1])/(x_values[i2]-x_values[i1])(即dy/dx)计算该间隔的斜率.
  3. x处的值现在是x1处的值加上斜率乘以距x1处的距离.
  1. Find the indices of the values in x_values which define an interval containing x. For instance, for x=3 with your example lists, the containing interval would be [x1,x2]=[2.5,3.4], and the indices would be i1=1, i2=2
  2. Calculate the slope on this interval by (y_values[i2]-y_values[i1])/(x_values[i2]-x_values[i1]) (ie dy/dx).
  3. The value at x is now the value at x1 plus the slope multiplied by the distance from x1.

您还需要确定如果xx_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆