关于在定义浮点数打印不会丢失精度,而在经过运算之后可能会丢失精度的问题
System.out.println(0.3f-0.2f);
System.out.println(0.1f);
输出
0.10000001
0.1
问:第一次打印丢失精度可以理解,但第二次为何不会丢失精度
答:还是精度问题,首先由于十进制转换成二进制本身是有一定的误差的,因此0.1存储在计算机中本身不是0.1而是一个极其接近的值,但是在print的时候经过计算机的精度取舍进位,最终又展示出来了0.1,而如果是0.3d-0.2d存储有了一次精度损失,计算又有一次精度损失,那么最终结果计算出来就没法得到0.1的结果。
这个打印时最终用的转换规则是 Double.ToString 的规则:
How many digits must be printed for the fractional part of m or a? There must be at least one digit to represent the fractional part, and beyond that as many, but only as many, more digits as are needed to uniquely distinguish the argument value from adjacent values of type double. That is, suppose that x is the exact mathematical value represented by the decimal representation produced by this method for a finite nonzero argument d. Then d must be the double value nearest to x; or if two double values are equally close to x, then d must be one of them and the least significant bit of the significand of d must be 0.
为啥0.1f 打印结果是 0.1 呢,因为,虽然 f 不是 0.1,但是 0.1 与 f 之间的差距,比任何其它double 类型浮点数都小。
打印时选择有效数字的依据是,打印结果与内存中的精确值的差距,要小于打印值与任何其它浮点数的差距。就是在所有浮点数中,打印结果与内存中的精确值最接近。在满足这个条件的基础上,有效数字的位数越少越好。
可以尝试在计算机上执行分别执行:
System.out.println(0.09999999999999998d);
System.out.println(0.099999999999999999d);
输出
0.09999999999999998
0.1