java 双精度浮点数,如何避免Java中的浮点数或双精度浮点精度错误?

I have a very annoying problem with long sums of floats or doubles in Java. Basically the idea is that if I execute:

for ( float value = 0.0f; value < 1.0f; value += 0.1f )

System.out.println( value );

What I get is:

0.0

0.1

0.2

0.3

0.4

0.5

0.6

0.70000005

0.8000001

0.9000001

I understand that there is an accumulation of the floating precision error, however, how to get rid of this? I tried using doubles to half the error, but the result is still the same.

Any ideas?

解决方案

There is a no exact representation of 0.1 as a float or double. Because of this representation error the results are slightly different from what you expected.

A couple of approaches you can use:

When using the double type, only display as many digits as you need. When checking for equality allow for a small tolerance either way.

Alternatively use a type that allows you to store the numbers you are trying to represent exactly, for example BigDecimal can represent 0.1 exactly.

Example code for BigDecimal:

BigDecimal step = new BigDecimal("0.1");

for (BigDecimal value = BigDecimal.ZERO;

value.compareTo(BigDecimal.ONE) < 0;

value = value.add(step)) {

System.out.println(value);

}

See it online: ideone

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值