Search code examples
javascriptarraysfor-loopfloating-pointsquare

Square values in an array (JavaScript) plus floating point error


I am following the first and second answer here. I have subtracted the mean from the value then console.log() it to check it out. I then use a for-loop to iterate through each value like:

for (var i = 0; i < myArray.length; i++) {
    Math.pow(squaredArray[i], 2);
};

I am also now getting a floating point error it looks like when I added the for-loop to square the values.

What am I doing wrong?

Fiddle here.


Solution

  • It looks like you're trying to loop through the values in myArray, square them, and store them in squaredArray.

    for (var i = 0; i < myArray.length; i++) {
        squaredArray[i] = Math.pow(myArray[i], 2);
    };
    

    The "floating point error" was because you were trying to do this:

    Math.pow(undefined, 2);