3

I have this code:

while (x < 10.0) {
    x += y;
}

If x and y are floating point numbers, apparently if you add them the loop will continue infinitely. I don't understand how it wont pass 10. It seems impossible to not pass ten but it doesn't according to my text book.

Why is that? Is it because of the rounding that happens with floating points? Or am I missing something?

Edit: x and y are strictly postive by the way

arshajii
  • 127,459
  • 24
  • 238
  • 287
user1832483
  • 107
  • 2
  • 8

3 Answers3

8

You haven't told us the actual initial values of x or y, so we can't say for sure. But here's an example of why this might not work:

class Main {
    public static void main(String[] args) {
        float x = 1.0f;
        float y = 1e-8f;
        float z = x + y;

        System.out.printf("%g\n", x);      // 1.00000
        System.out.printf("%g\n", y);      // 1.00000e-08
        System.out.printf("%g\n", z);      // 1.00000
        System.out.printf("%g\n", z - x);  // 0.00000

    }
}

See http://ideone.com/RMMPlP.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • And an example where it could theoretically work, you just haven't waited long enough: `y = 1e-30f` :-) – Adrian Pronk Jun 04 '13 at 00:51
  • Yes see this is what I mean I plugged in the code and it just keeps running but why is that thought what makes floating point numbers just keep going like that. – user1832483 Jun 04 '13 at 00:56
  • @user1832483: Because in floating point, 1.0 + 1e-8 == 1.0. You need to review how floating-point works ;) – Oliver Charlesworth Jun 04 '13 at 00:57
  • @OliCharlesworth: I just meant to joke that even if the precision was sufficient so adding 1e-30f would result in a higher value, because the loop would have to iterate about 1e30 times it would effectively be an infinite loop anyway. – Adrian Pronk Jun 04 '13 at 01:41
0

Your y value may be 0 or very small and hence making the loop to run for infinte or for a long time:

Assuming if

y = 0;

This loop will go infinite

while(x < 10.0) {
x += y;
}
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

Are you using Java?Try this-

while(x < 10.0f) {
x += y;
}

or

while(x < (float)10.0) {
x += y;
}
Flying Monkey
  • 669
  • 1
  • 5
  • 13