Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to normalize any number from 0 - 1

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.

like image 844
Marquizzo Avatar asked Sep 29 '16 17:09

Marquizzo


People also ask

Why do we normalize data between 0 and 1?

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.

How do you normalize a zero?

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.


2 Answers

Why not just:

function(val, max, min) { return (val - min) / (max - min); } 
like image 96
Nathan Berton Avatar answered Oct 06 '22 01:10

Nathan Berton


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)));
like image 45
Nina Scholz Avatar answered Oct 06 '22 00:10

Nina Scholz