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.
Standardization: Standardizing the features around the center and 0 with a standard deviation of 1 is important when we compare measurements that have different units. Variables that are measured at different scales do not contribute equally to the analysis and might end up creating a bais.
You can determine the mean of the signal, and just subtract that value from all the entries. That will give you a zero mean result. To get unit variance, determine the standard deviation of the signal, and divide all entries by that value.
Why not just:
function(val, max, min) { return (val - min) / (max - min); }
Using Nathan Bertons's answer with a preconfigured function for some values with the same min
and max
values, you could use this.
function normalize(min, max) { var delta = max - min; return function (val) { return (val - min) / delta; }; } console.log([5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15].map(normalize(5, 15)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With