Skip to content

Instantly share code, notes, and snippets.

@robbeman
Last active February 12, 2019 15:57
Show Gist options
  • Save robbeman/656ef76bb45073b3b97c to your computer and use it in GitHub Desktop.
Save robbeman/656ef76bb45073b3b97c to your computer and use it in GitHub Desktop.
linear interpolation
/*handy arrow function definitions*/
/*
const lerp = (a,b,x) => a+x*(b-a);
const qarp = (a,b,c,x) => lerp(lerp(a,b,x),lerp(b,c,x),x);
const unlerp = (a,b,y) => (y-a)/(b-a);
const lerpUnlerp = (a, b, c, d, x) => a+((x-c)/(d-c))*(b-a);
*/
/**
* Linear interpolation
*
* Example:
* lerp(0,10,0.5) => 5
* lerp(65,84,0.5) => 74.5
*
* @param {Number} min The "minimum" output value
* @param {Number} max The "maximum" output value
* @param {Number} x The input value to interpolate
*/
export function lerp(min,max,x){
return x*(max-min)+min;
}
/**
* Reversed linear interpolation
*
* Example:
* unlerp(0,10,5) => 0.5
* unlerp(87,167,127) => 0.5
*
* @param {Number} min The "minimum" input value
* @param {Number} max The "maximum" input value
* @param {Number} x The input value to unlerp
*/
export function unlerp(min,max,x){
return (x-min)/(max-min);
}
/**
* This is essentially the same as calling `lerp(minOutput, maxOutput, unler(minInput, maxInput, x))`, but requires one less function call.
* @param {Number} minOutput The "minimum" output value
* @param {Number} maxOutput The "maximum" output value
* @param {Number} minInput The lower result (unlerp) value
* @param {Number} maxInput The upper result (unlerp) value
* @param {Number} x The input value
*/
export function lerpUnlerp(minOutput, maxOutput, minInput, maxInput, x) {
return minOutput+((x-minInput)/(maxInput-minInput))*(maxOutput-minOutput);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment