java浮点型判断相等,Java中的浮点精度和相等性

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值