0

I tried a this simple for loop using both a double and a float and I am getting different results and I don't know why

    for (double i = 0; i < 1; i += 0.1) cout << i << endl;

for that I get the following output 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 and I do not understand why 1 is being an output when it should clearly break the for loop condition. However when I change the type from double to float like so:

     for (float i = 0; i < 1; i += 0.1) cout << i << endl;

then I get the following output as I would expect 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9

And in this case, I do not get 1 as an output since when i=1 it will break the loop condition. I cannot understand what is going on, I have run this in Visual Studio several times with the same result.

Scott Madeux
  • 329
  • 3
  • 8
  • 5
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Eljay Jul 14 '21 at 14:04
  • 1
    Often, in computer science, the solution is to use a smaller discrete unit. `for(int tenth = 0; tenth < 10; tenth ++)` and then write logic that uses an integral number of tenths as opposed to a floating point number. Especially with money. – Jeffrey Jul 14 '21 at 14:08
  • 3
    The value `0.1` (decimal) cannot be exactly represented in floating point. The reason is the same that `1/3` cannot be represented exactly in decimal (base 10) - the representation is infinite. The only difference is that floating point types work in base 2, and `0.1` cannot be represented exactly as the sum of a finite number of negative powers of two (1/2, 1/4, 1/8, 1/16, etc). `float` has lower precision than `double`, so a `double` can represent `0.1` more precisely, but not exactly - but `0.1f` will not test as equal to `0.1`. – Peter Jul 14 '21 at 14:21

0 Answers0