Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

85
Vistas
Lagrange Interpolating Polynomial Algorithm in Javascript

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],
]

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
  )
)

Did I make a mistake with my code?

Thank you,

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos