Floating point precision and equality in Java -


it's know floating point number, fixed digits after decimal point in decimal format, can't represented exactly. have following program test:

public class main {   public static void main(string[] args) {     system.out.printf("0.1 in single precision %.50f\n", 0.1f);     system.out.printf("0.2 in single precision %.50f\n", 0.2f);     system.out.printf("0.3 in single precision %.50f\n", 0.3f);     system.out.printf("0.1 + 0.2 in single precision %.50f\n", 0.1f + 0.2f);     system.out.printf("0.1 + 0.2 == 0.3 %b in single precision\n", 0.1123f * 0.4f + 0.2f * 0.5f == 0.2f * 0.7f + 0.0123f * 0.4f);      system.out.println();      system.out.printf("0.1 in double precision %.50f\n", 0.1);     system.out.printf("0.2 in double precision %.50f\n", 0.2);     system.out.printf("0.3 in double precision %.50f\n", 0.3);     system.out.printf("0.1 + 0.2 in double precision %.50f\n", 0.1 + 0.2);     system.out.printf("0.1 + 0.2 == 0.3 %b in double precision\n", 0.1 + 0.2 == 0.3);   } } 

the output following:

0.1 in single precision 0.10000000149011612000000000000000000000000000000000 0.2 in single precision 0.20000000298023224000000000000000000000000000000000 0.3 in single precision 0.30000001192092896000000000000000000000000000000000 0.1 + 0.2 in single precision 0.30000001192092896000000000000000000000000000000000 0.1 + 0.2 == 0.3 true in single precision  0.1 in double precision 0.10000000000000000000000000000000000000000000000000 0.2 in double precision 0.20000000000000000000000000000000000000000000000000 0.3 in double precision 0.30000000000000000000000000000000000000000000000000 0.1 + 0.2 in double precision 0.30000000000000004000000000000000000000000000000000 0.1 + 0.2 == 0.3 false in double precision 

two questions can't answer above result , seeking for:

  1. why double representation of 0.1, 0.2 , 0.3 looks exact, whereas 0.1 + 0.2 doesn't.
  2. why 0.1f + 0.2f == 0.3f return true?

  1. i suspicious of system.out.printf working correctly here. reliable way exact double value when write 0.1 write new bigdecimal(0.1).tostring().
  2. "why 0.1f + 0.2f == 0.3f return true?" pretty because got lucky: rounding 0.1 closest float representation , 0.2 closest float representation , adding them gets closest representable float 0.3. that's not true in general, values happen work.

Comments