問題描述
我有一個非常煩人的問題,即 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.
- 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.
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模板網!