-1

I'm trying to make a simple summation of an array of 10 numeric elements.
I get a totally incorrect result, which only occurs with an array of certain values, otherwise works well.

var sum = 0;
var values = [14, -1.4, -1.4, -1.4, -1.4, -1.4, -1.4, -1.4, -1.4, -1.4, -1.4];
for (var i = 0; i < values.length; i++) {
  var v = values[i];
  sum += v;
}
console.log(sum);

The expected result is 0, but I get oddly -2.22!
At other times, I have achieved results with so many decimal places, which I had to round up.
But in this case, with these numbers, that kind of bug is absurd.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
T. Phanelly
  • 189
  • 5
  • 17

2 Answers2

0

Your code works fine, it has to do with the imprecision of floats. When you multiple each value by 10 (so 1.4 becomes 14) before doing your calculation the end result is 0.

See also How to deal with floating point number precision in JavaScript?

var sum = 0;
var values = [14, -1.4, -1.4, -1.4, -1.4, -1.4, -1.4, -1.4, -1.4, -1.4, -1.4];
for(var i=0; i<values.length; i++){
    var v = values[i];
    sum += (v * 10);
}
sum = sum / 10;
console.log(sum);
Thijs
  • 2,341
  • 2
  • 14
  • 22
0

console.log(1.3999999999999977 + -1.4);

in the end due to precision loss you operate on the above expression, this is equivalent to 2.2 * 10^(-15) which is the precision loss you got along the way

marvel308
  • 10,288
  • 1
  • 21
  • 32