Home > Mobile >  Lagrange Interpolating Polynomial Algorithm in Javascript
Lagrange Interpolating Polynomial Algorithm in Javascript

Time:11-04

I implemented a formula from this link https://www.dcode.fr/lagrange-interpolating-polynomial to calculate some kind of score between coordinates.

The result value worked as expected with coordinates like

const coordinates = [
  [0, 100], 
  [2.5, 70],
  [10, 30],
]
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

where y axis are even numbers but with y value like 67, 33 is not working as expected.

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
  )
)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Did I make a mistake with my code?

Thank you,

CodePudding user response:

The algorithm is working as it should, though not as you expect.

That algorithm fits a polynomial to the points. If you have 3 points, it will be a parabola. Because it falls so fast over the first 2 points, that parabola will have its minimum between the second two, and therefore gives values below the numbers you gave.

If this is not the kind of interpolation that you want, I would suggest that you use a non-polynomial. For example you could play around with a weighted average that looks something like this:

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

Make f(x) be a function that has f(x) = f(-x) and blows up at 0. Of course if you're at that point, just enter the value of that point. For example 1/x^2. This will cause you to every be close to a reasonable average of the nearby points.

  • Related