I'm trying to make a function that takes a number and normalizes it from 0 - 1 between its min and max bounds. For example:
If I want to normalize a value of 10 between 5 to 15, I call this:
val = 10; normalize(val, 5, 15);
Returns 0.5
normalizing a value 0 between -10 and 5
val = 0; normalize(val, -10, 5);
Returns 0.666
This is the function I came up with:
function normalize(val, min, max){
// Shift to positive to avoid issues when crossing the 0 line
if(min < 0){
max += 0 - min;
val += 0 - min;
min = 0;
}
// Shift values from 0 - max
val = val - min;
max = max - min;
return Math.max(0, Math.min(1, val / max));
}
My question is: Is this the most efficient method to normalize a 1-dimensional value? I'm going to be calling this function a few thousand times per frame at 60fps, so I'd like to have it as optimized as possible to reduce the burden of calculation. I've looked for normalization formulas, but all I find are 2- or 3-dimensional solutions.
Why not just:
function(val, max, min) { return (val - min) / (max - min); }