Search code examples
javascriptloopsfloating-point-precision

javascript loops give different results


This is probably a question with an really logical answer.. But I really don't understand this!!

Why, does this give different results..

Only difference is a for loop and a while loop.. Even while they loop exactly as many times???

array = [1.2344, 2.47373, 3.444];

    var total = 0,
        total2 = 0,
        i = array.length,
        whileLoops = 0,
        forLoops = 0;

    while (i--) {
        whileLoops++;
        total += array[i];
    }

    for (var i = 0, len = array.length; i < len; i++) {
        forLoops++;
        total2 += array[i];
    }

    if (total !== total2) {
        console.log("BOE")
    }

I tried parseFloat, but this also wasn't helping :(

It it because the Javascript engine rounds numbers in a sort of way???

On request: the fiddle http://jsfiddle.net/5dsx0ump/

UPDATE

Would the solution be to first to a * 1000 and after all the calculations, divide again by 1000, to keep round numbers?


Solution

  • The difference in the loops is the order that you add the numbers.

    For each of those additions there is a tiny loss of data, as the result has to fit in the same data type as both the operands. What's lost depends on what the numbers are, so adding the numbers in different order causes a small difference in the result in the end.

    If you print out the numbers, they may or may not look the same, but looking the same when printed doesn't mean that they must have the same value. The numbers have a precision of 15-17 digits, but that is rounded to slightly less when printed, just to avoid seeing the limitation in precision.

    This is normal behaviour for floating point numbers, and you would see the same result in any programming language using floating point numbers. Floating point numbers are simply not exact, so in application where numbers actually have to be exact (e.g. banking), other data types are used.