关于在定义浮点数打印不会丢失精度,而在经过运算之后可能会丢失精度的问题

关于在定义浮点数打印不会丢失精度,而在经过运算之后可能会丢失精度的问题

        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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sen.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值