-3

I'm adding up some floats in a loop. I expected that when i reaches 9, the sum will be equal to 1, and NSLog(@"EXTRA: %f", sum); will be executed. It is never executed... what is going on here?

Here is my code:

float number = 0.1;
float sum = 0;

for (int i = 0; i < 1000; i++) {
    sum += number;

    if (sum == 1) {
        NSLog(@"EXTRA: %f", sum);
    }
    NSLog(@"%f", sum);
}
jscs
  • 63,694
  • 13
  • 151
  • 195
MegaManX
  • 8,766
  • 12
  • 51
  • 83

1 Answers1

3

The binary value of 1/10 is like the Denary value of 1/3 - it reccurs. In fact, the value of 1/10 stored in the variable is 0.0001100110011001100110011....

But the length of this number is limited by the float length, or a 32 / 64 bit OS.

So when I add 0.000110011 to 0.000110011 I get 0.001100110 which is not quite 2/10, the same as 0.333333 + 0.333333 =! 2/3 - it equals 0.66666.

This is happening 9 times, and so 1/10 * 10 in binary doesn't equal 1, it's 0.111111111 which equals 0.998046875 - a long way off 1.

To more decimal places (e.g. 30) 0.000110011001100110011001100110 * 1010 = 0.111111111111111111111111111100 or 0.999999996274709701538085937500. Which is not quite 1.

Ry-
  • 218,210
  • 55
  • 464
  • 476
Tim
  • 2,563
  • 1
  • 23
  • 31
  • Please don't go editing lots of questions just to add pronouns, it spams the front page with all of your changes. – DavidG Oct 17 '19 at 13:48