知道浮点数,即使十进制格式小数点后的固定位数,也无法准确表示。所以我有以下程序要测试:
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);
}
}
输出如下:
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
我无法从上述结果中回答两个问题,我正在寻求帮助:
0.1
,0.2
和0.3
的双重表示看起来很精确,而0.1 + 0.2
则不然。0.1f + 0.2f == 0.3f
会返回true?答案 0 :(得分:2)
System.out.printf
在这里工作正常。获得写入0.1时获得的确切double
值的可靠方法是写new BigDecimal(0.1).toString()
。