【问题标题】:How to find points by linear interpolation如何通过线性插值求点
【发布时间】:2016-10-18 23:00:30
【问题描述】:

我有两个点 (5,0.45) & (6,0.50),需要通过线性插值求 x=5.019802 时的值

但是如何在 R 中编码呢?

我尝试了下面的代码,但得到了一个图表。

x <- c(5,6)
y <- c(0.45,0.50)

interp <- approx(x,y)

plot(x,y,pch=16,cex=2)
points(interp,col='red')

【问题讨论】:

  • 精确值 5.019802,不会出现在 interp$x 中。您可以尝试使用 targetVal = 5.019802 ; which.min(abs(interp$x - targetVal )) 将索引设为 2 来找到最接近目标值的点,interp$x[2],interp$y[2] 将是最接近所需值的点

标签: r linear-interpolation


【解决方案1】:

您只需要指定一个xout 值。

approx(x,y,xout=5.019802)
$x
[1] 5.019802

$y
[1] 0.4509901

【讨论】:

    【解决方案2】:

    我建议创建一个求解 y = mx + b 的函数。

    x = c(5,6)
    y = c(0.45, 0.50)
    m <- (y[2] - y[1]) / (x[2] - x[1]) # slope formula
    b <- y[1]-(m*x[1]) # solve for b
    m*(5.019802) + b
    
    # same answer as the approx function
    [1] 0.4509901
    

    【讨论】:

      猜你喜欢
      • 2018-09-20
      • 1970-01-01
      • 2011-05-20
      • 1970-01-01
      • 2019-06-27
      • 1970-01-01
      • 1970-01-01
      • 2018-01-22
      • 1970-01-01
      相关资源
      最近更新 更多