Normalizing Data Using Javascript

2019-09-10 20:06发布

问题:

I have multiple arrays of size 262144, and I am trying to use the following code to set all the values of each array to between 0 and 1, inclusive. To be clear, each array will be normalized differently because each has different values.

var i;
var max = Number.MIN_VALUE;
var min = Number.MAX_VALUE;
for (i = 0; i < array.length; i++) {
    if(array[i]>max) {
        max = array[i];
    }
}

for (i = 0; i < array.length; i++){
    if(array[i]<min) {
        min = array[i];
    }
}

for (i = 0; i < array.length; i++) {
    var norm = (array[i]-min)/(max-min);
    array[i] = norm;
}

However, I know that it's not doing this correctly because when I do the following code, the numbers logged to the console are often above 1.

max = Number.MIN_VALUE;
min = Number.MAX_VALUE;
for (i = 0; i < array.length; i++) {
    if(array[i]>max) {
        max = array[i];
    }
}

for (i = 0; i < array.length; i++) {
    if(array[i]<min) {
        min = array[i];
    }
}

console.log(max);
console.log(min);

What am I doing wrong? Thank you!

回答1:

Your code works fine for me. The following example results in the following normalized array:

[
  0,
  0.821917808219178,
  0.0684931506849315,
  0.3835616438356164,
  1
]

Note that min and max do not have to be between 0 and 1 since they represent the minimal and maximal value of your original array.

var array = [4, 64, 9, 32, 77];

var i;
var max = Number.MIN_VALUE;
var min = Number.MAX_VALUE;
for (i = 0; i < array.length; i++)
{
   if(array[i]>max)
   {
       max = array[i];
   }
}

for (i = 0; i < array.length; i++)
{
   if(array[i]<min)
   {
       min = array[i];
   }
}

for (i = 0; i < array.length; i++)
{
   var norm = (array[i]-min)/(max-min);
   array[i] = norm;
}

max = Number.MIN_VALUE;
min = Number.MAX_VALUE;
for (i = 0; i < array.length; i++) {
    if(array[i]>max) {
        max = array[i];
    }
}

for (i = 0; i < array.length; i++) {
    if(array[i]<min) {
        min = array[i];
    }
}

console.log(array);

console.log(max); // 1
console.log(min); // 0

Edit: As you can see in the example, the min and max value after the normalization should be 0 and 1, which is the case.



回答2:

I found the solution thanks to this answer! It's simply that the numbers were being compared as I had not converted them from strings to floats.