問(wèn)題描述
我有一個(gè)非常煩人的問(wèn)題,即 Java 中的浮點(diǎn)數(shù)或雙精度數(shù)很長(zhǎng).基本上這個(gè)想法是,如果我執(zhí)行:
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
我知道有浮動(dòng)精度誤差的累積,但是,如何擺脫這個(gè)?我嘗試使用 doubles 將錯(cuò)誤減半,但結(jié)果還是一樣.
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.
有什么想法嗎?
推薦答案
沒(méi)有將 0.1 精確表示為 float
或 double
.由于這種表示錯(cuò)誤,結(jié)果與您的預(yù)期略有不同.
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:
- 當(dāng)使用
double
類(lèi)型時(shí),只顯示你需要的數(shù)字.在檢查相等性時(shí),無(wú)論哪種方式都允許有一個(gè)小的容差. - 或者使用允許您存儲(chǔ)要精確表示的數(shù)字的類(lèi)型,例如
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
這篇關(guān)于如何避免 Java 中的浮點(diǎn)數(shù)或雙精度數(shù)的浮點(diǎn)精度錯(cuò)誤?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!