0

Could someone tell me why this loop is an infinite loop?

double count = 0.0;
while( count != 1.0)
{count += 1.0/10;}

And why this loop is not an infinite loop

double count = 0.0;
while( count != 1.0)
{count += 1.0/3;}

I've been trying to wrap my head around this as a beginner and it really isn't making sense for me.

Uli Köhler
  • 13,012
  • 16
  • 70
  • 120

3 Answers3

0

The reason is due to double precision.

Here's a post that might help explain some more Java precision during division and multiplication alterneting process

Community
  • 1
  • 1
fxfilmxf
  • 582
  • 6
  • 13
0

Floating point division is involved in both cases. Floating point divisions are notorious for giving round off values, which are nearly the same, but not exactly.

Since your conditions in both the while loops are that of equality, it's a logical deduction that in the first one, the round off is happening such that it can't reach exactly 1.0, while in the other, the round off is such that it is able to reach exactly 1.0.

A word of advice: Don't use such code in production level.

Aman Agnihotri
  • 2,973
  • 1
  • 18
  • 22
0

Because of the way double are added on the first case count will never be == 1.0 so you'll end up in an infinite cycle. The amount of count on this cycle in each iteration is:

count: 0.1 count: 0.2 count: 0.30000000000000004 count: 0.4 count: 0.5 count: 0.6 count: 0.7 count: 0.7999999999999999 count: 0.8999999999999999 count: 0.9999999999999999 (This number is different than 1.0) count: 1.0999999999999999 count: 1.2 count: 1.3 [...]

On the second cycle counter does == 1.0 so it ends. The amount of count on the second cycle in each iteration is:

count: 0.3333333333333333 count: 0.6666666666666666 count: 1.0