It's know that floating point number, even those with fixed digits after decimal point in decimal format, can't be represented exactly. So I have the following program to test:
public class Main {
public static void main(String[] args) {
System.out.printf("0.1 in single precision is %.50f\n", 0.1f);
System.out.printf("0.2 in single precision is %.50f\n", 0.2f);
System.out.printf("0.3 in single precision is %.50f\n", 0.3f);
System.out.printf("0.1 + 0.2 in single precision is %.50f\n", 0.1f + 0.2f);
System.out.printf("0.1 + 0.2 == 0.3 is %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 is %.50f\n", 0.1);
System.out.printf("0.2 in double precision is %.50f\n", 0.2);
System.out.printf("0.3 in double precision is %.50f\n", 0.3);
System.out.printf("0.1 + 0.2 in double precision is %.50f\n", 0.1 + 0.2);
System.out.printf("0.1 + 0.2 == 0.3 is %b in double precision\n", 0.1 + 0.2 == 0.3);
}
}
The output is the following:
0.1 in single precision is 0.10000000149011612000000000000000000000000000000000
0.2 in single precision is 0.20000000298023224000000000000000000000000000000000
0.3 in single precision is 0.30000001192092896000000000000000000000000000000000
0.1 + 0.2 in single precision is 0.30000001192092896000000000000000000000000000000000
0.1 + 0.2 == 0.3 is true in single precision
0.1 in double precision is 0.10000000000000000000000000000000000000000000000000
0.2 in double precision is 0.20000000000000000000000000000000000000000000000000
0.3 in double precision is 0.30000000000000000000000000000000000000000000000000
0.1 + 0.2 in double precision is 0.30000000000000004000000000000000000000000000000000
0.1 + 0.2 == 0.3 is false in double precision
Two questions I can't answer from the above result and I am seeking help for:
Why does the double representation of 0.1, 0.2 and 0.3 looks exact, whereas 0.1 + 0.2 doesn't.
Why does 0.1f + 0.2f == 0.3f return true?
解决方案I am suspicious of System.out.printf working correctly here. A reliable way to get the exact double value you get when you write 0.1 is to write new BigDecimal(0.1).toString().
"Why does 0.1f + 0.2f == 0.3f return true?" Pretty much because you just got lucky: rounding 0.1 to the closest float representation and 0.2 to the closest float representation and adding them gets you the closest representable float to 0.3. That's not true in general, those values just happen to work.