I can’t seem to find the reason why the below code is breaking:
From my perspective what happens is that the integer lbnd is decreased
public class Test {
public static void main(String[] args) {
methode1();
}
static void methode1() {
int ubnd = Integer.MAX_VALUE;
int lbnd = ubnd;
while ((float)lbnd == (float)ubnd) {
--lbnd;
}
System.out.println((++lbnd) + ".." + ubnd);
}
}
the thing is that this loop should be an infinite loop from what I see, however it breaks after 64 loops because the ints changed in value. The outcome is:
2147483584..2147483647
but it should be an infinite loop with:
2147483647..2147483647
Remember that a float does not have sufficient precision to store all 32 bits of an integer precisely. So for an integer of high magnitude, (float) i and (float) (i-1) are identical for the purposes of a float comparison.
(Incidentally, when comparing an int and a float, it will be treated as a float comparison. So to illustrate an additional gotcha, you don’t even need the cast to float on one side of your == comparison.)