我有一个非常烦人的问题,即 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 );
我得到的是:
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.70000005
0.8000001
0.9000001
我知道有浮动精度误差的累积,但是,如何摆脱这个?我尝试使用 doubles 将错误减半,但结果还是一样.
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.
有什么想法吗?
没有将 0.1 精确表示为 float
或 double
.由于这种表示错误,结果与您的预期略有不同.
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:
double
类型时,只显示你需要的数字.在检查相等性时,无论哪种方式都允许有一个小的容差.BigDecimal
可以精确表示 0.1.double
type, only display as many digits as you need. When checking for equality allow for a small tolerance either way.BigDecimal
can represent 0.1 exactly.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);
}
在线查看:ideone
这篇关于如何避免 Java 中的浮点数或双精度数的浮点精度错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!