S
slebetman
Dik said:But that is not really the problem, because in that case 0.4999...999 will
compare equal to 0.5 (assuming a well-behaved floating-point system). On
the other hand, it *is* possible that you have a number that compares
smaller than 0.5 but where adding 0.5 to that number results in 1.0.
The following program:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
double d = 0.25, r;
int i = 0;
r = d;
while(d < 0.5) {
if(d + 0.5 == 1.0) {
printf("equal at step %d\n", i);
exit(0);
}
r = r / 2;
i++;
d += r;
}
}
Will print
equal at step 52
on a Sun running Solaris, it will print
equal at step 63
on an Intel machine using gcc with -O3, and it will
print nothing on that same machine using gcc without
optimisation (but will termate). So under some circumstances
we have a number that is smaller than 0.5 but where
floor(x + 0.5) will yield 1.0.
Nicely illustrated. And it can be tested even on non "weird"
implementations ;-)