0

I've been working on some code and hade to write this for loop:

for(double i = -1; i <= 1; i += 0.1) {
      cout << i << "\n";
}

The weird thing is that when I run the code above, I get the following values:

-1
-0.9
-0.8
-0.7
-0.6
-0.5
-0.4
-0.3
-0.2
-0.1
-1.38778e-16
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1

At the middle, instead of getting 0, I get this number: -1.38778e-16. Can you please explain why this is happening and how I can fix this?

  • floating point math error, i guess, you should loop over integers instead of decimal numbers, and divide them by 10 when needed – Drdilyor May 30 '21 at 17:43
  • .1 cannot be precisely represented in binary. Hence, adding 10 .1's will not result in exactly 1.0 There are numerable examples here. Search is floating point broken. – doug May 30 '21 at 17:45
  • Floating-point arithmetic does not follow the rules that you're used to from working with real numbers. It's close enough that people often get surprised by the differences. – Pete Becker May 30 '21 at 18:01

0 Answers0