// Ian! D. Allen - idallen@idallen.ca - www.idallen.com // FunnyMath1 - wrong answers for simple floating comparisons // Compile and run this program. Look at the output. // Explain why all of the outputs are incorrect. // // Change the declaration of "f" to "double" (one change) and try again. // Explain what you see. public class FunnyMath1 { public static void main(String[] args) { float f; System.out.println( "Inaccurate floating-point comparison attempts" ); System.out.println( "" ); // Why do these numbers compare as equal? // How big does f need to be before they are not equal? f = 16777217.0f; if ( f == 16777216.0f ) { System.out.println( "The numbers 16777217.0f and 16777216.0f are Equal! WHY?" ); } else { System.out.println( "Unequal." ); } System.out.println( "Different views of the number 16777217.0f :" ); System.out.println( "f: " + f ); System.out.printf( "f: %.40f\n", f ); System.out.printf( "f: %.40a\n", f ); System.out.println( "" ); // Why do these numbers compare as equal? // How big does f need to be before they are not equal? f = 1125899909999999.0f; if ( f == 1125899906842624.0f ) { System.out.println( "The numbers 1125899909999999.0f and 1125899906842624.0f are Equal! WHY?" ); } else { System.out.println( "Unequal." ); } System.out.println( "Different views of the number 1125899909999999.0f :" ); System.out.println( "f: " + f ); System.out.printf( "f: %.40f\n", f ); System.out.printf( "f: %.40a\n", f ); System.out.println( "" ); // Why do these numbers compare as equal? // How big does f need to be before they are not equal? // hex float value 0x1.0p126 is 2**126 - approximately 8.507059e37 f = 0x1.0p126f + 10000000000000000000000000000f; if ( f == 0x1.0p126f ) { System.out.println( "The numbers 0x1.0p126f + 10000000000000000000000000000f and 0x1.0p126f are Equal! WHY?" ); } else { System.out.println( "Unequal." ); } System.out.println( "Different views of the number 0x1.0p126f + 10000000000000000000000000000f :" ); System.out.println( "f: " + f ); System.out.printf( "f: %.40f\n", f ); System.out.printf( "f: %.40a\n", f ); System.out.println( "" ); } }