【问题标题】:Lagrange Interpolating Polynomial Algorithm in JavascriptJavascript中的拉格朗日插值多项式算法
【发布时间】:2021-12-16 10:15:37
【问题描述】:

我从这个链接https://www.dcode.fr/lagrange-interpolating-polynomial 实现了一个公式来计算坐标之间的某种分数。

结果值在坐标下按预期工作

const coordinates = [
  [0, 100], 
  [2.5, 70],
  [10, 30],
]

其中 y 轴是偶数,但 y 值如 67、33 未按预期工作。

function getScore (thresholds, macro) {
  let value = 0
  
  for (let j = 0; j < thresholds.length; j++) {
    let temp = 1

    for (let i = 0; i < thresholds.length; i++) {
      if (i !== j) {      
        temp *= (macro - thresholds[i][0]) / (thresholds[j][0] - thresholds[i][0])
      }
    }

    value += thresholds[j][1] * temp
  }
  
  return value
}

console.log(
  'Expecting Something above 33 but get 31',
  getScore(    
    [
      [0, 100], 
      [2.5, 66],
      [10, 33],
    ],
    9
  )
)

console.log(
  'Expecting Something above 30 but and got 31',
  getScore(    
    [
      [0, 100], 
      [2.5, 70],
      [10, 30],
    ],
    9
  )
)

我的代码有误吗?

谢谢,

【问题讨论】:

    标签: javascript algorithm


    【解决方案1】:

    算法运行正常,但与您的预期不同。

    该算法将多项式拟合到这些点。如果你有 3 个点,它将是一条抛物线。因为它在前 2 个点上下降得如此之快,所以抛物线将在后两个点之间有最小值,因此给出的值低于您给出的数字。

    如果这不是您想要的插值,我建议您使用非多项式。例如,您可以使用看起来像这样的加权平均值:

    sum(point.y * f(x - point.x) for point in points)
        /
    sum(f(x - point.x) for point in points)
    

    使f(x) 成为具有f(x) = f(-x) 并在0 处爆炸的函数。当然,如果您处于该点,只需输入该点的值即可。例如1/x^2。这将使您每个人都接近附近点的合理平均值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多