Search code examples
javascriptmath

Javascript lerp fuction not giving accurate answers


I need to interpolate between three different ranges, (1,1.3),(.72,1) , (1.4,1.9)->(1,1.05) and (2,3)->(1.05,1.1) where the first two items are x values, and the 2nd two are the y's, but the function doesn't seem to return the right values, even for the given points,

Any help appreciated.

function lerp(x1, x2, y1, y2, x) {
  return y1 + (x2 - x1) * (y2 - y1) / (x2 - x1);
}

function savings(t) {
  let res;
  let m;
  if (t >= 1 || t <= 1.3) {
    res = lerp(1, 1.3, .72, 1, t);
    console.log(res)
  }
  if (t >= 1.4 || t <= 1.9) {
    res = lerp(1.4, 1.9, 1, 1.05, t);
    console.log(res)
  }
  if (t >= 2 || t <= 3) {
    res = lerp(2, 3, 1.05, 1.1, t);
    console.log(res)
  }

  return res;
}

savings(1.3)


Solution

  • You need to check the range by using the logical AND && operator instead of logical OR ||, which checks only one comparison.

    That means all values of t takes the first condition until all values are greater or equal than one.

    function lerp(x1, x2, y1, y2, x) {
        // Original lerp code from OP copied here, unrelated to question
        // Want a working lerp? Use:
        // return y1 + (y2-y1) * (x-x1) / (x2-x1)
        return y1 + (x2 - x1) * (y2 - y1) / (x2 - x1);
    }
    
    function savings(t) {
        if (t >= 1 && t <= 1.3) return lerp(1, 1.3, .72, 1, t);
        if (t >= 1.4 && t <= 1.9) return lerp(1.4, 1.9, 1, 1.05, t);
        if (t >= 2 && t <= 3) return lerp(2, 3, 1.05, 1.1, t);
    }
    
    console.log(savings(1.3));