問題描述
我想知道在 Java 中修復精度錯誤的最佳方法是什么.正如您在以下示例中看到的那樣,存在精度錯誤:
I'm wondering what the best way to fix precision errors is in Java. As you can see in the following example, there are precision errors:
class FloatTest
{
public static void main(String[] args)
{
Float number1 = 1.89f;
for(int i = 11; i < 800; i*=2)
{
System.out.println("loop value: " + i);
System.out.println(i*number1);
System.out.println("");
}
}
}
顯示的結果是:
循環值:11
20.789999
循環值:22
41.579998
循環值:44
83.159996
循環值:88
166.31999
循環值:176
332.63998
循環值:352
665.27997
循環值:704
1330.5599
另外,如果有人能解釋為什么它只從 11 開始,并且每次都將價值翻倍.我認為所有其他值(或至少其中許多值)都顯示了正確的結果.
Also, if someone can explain why it only does it starting at 11 and doubling the value every time. I think all other values (or many of them at least) displayed the correct result.
這樣的問題過去讓我很頭疼,我通常使用數字格式化程序或將它們放入字符串中.
Problems like this have caused me headache in the past and I usually use number formatters or put them into a String.
正如人們所提到的,我可以使用雙精度,但在嘗試之后,似乎 1.89 作為雙倍乘以 792 仍然會輸出錯誤(輸出為 1496.8799999999999).
As people have mentioned, I could use a double, but after trying it, it seems that 1.89 as a double times 792 still outputs an error (the output is 1496.8799999999999).
我想我會嘗試其他解決方案,例如 BigDecimal
I guess I'll try the other solutions such as BigDecimal
推薦答案
如果你真的很在意精度,你應該使用 BigDecimal
If you really care about precision, you should use BigDecimal
https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/math/BigDecimal.html
這篇關于Java中浮點數的精度錯誤的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!