Seems that there is an error when casting an int to a float, at least for certain values of the integer. The first integer to fail is 2^24... Note also that it's only odd integer values that are a problem. At least one other version (2.3.2) of gcc did not have this problem. -bash-2.05b$ gcc main_cast.c && ./a.out | head Size of integers: 4 Failed: 16777216.000000 != 16777217.000000 Failed: 16777220.000000 != 16777219.000000 Failed: 16777220.000000 != 16777221.000000 Failed: 16777224.000000 != 16777223.000000 Failed: 16777224.000000 != 16777225.000000 Failed: 16777228.000000 != 16777227.000000 Failed: 16777228.000000 != 16777229.000000 Failed: 16777232.000000 != 16777231.000000 Failed: 16777232.000000 != 16777233.000000 -bash-2.05b$ --- main_cast.c --- #include <stdio.h> #include <limits.h> int main() { int i; float f; printf( "Size of integers: %i\n", sizeof(int) ); for( i = 0; i < INT_MAX; i += 1 ) { f = (float)i; if( f != ((float)i) ) printf( "Failed: %f != %f\n", f, (float)i ); } return 0; }
*** This bug has been marked as a duplicate of 323 ***
Oops. floats only store 23 or 24 bits of mantissa. I guess it's a feature...