首頁  >  文章  >  Java  >  如果需要準確答案,請避免浮動和雙精度

如果需要準確答案,請避免浮動和雙精度

Barbara Streisand
Barbara Streisand原創
2024-10-10 08:08:29768瀏覽

Item  Evite o float e o double caso sejam necessárias respostas exatas

float 與 double 問題:

  • 專為科學和數學計算而設計,執行二元浮點運算。
  • 不適合貨幣計算或需要精確答案的情況。
  • 它們無法準確表示 10 的負冪,例如 0.1,這會導致錯誤。

範例1:
減去美元金額時計算錯誤:

System.out.println(1.03 - 0.42);  // Resultado: 0.6100000000000001

範例2:
以每件 10 美分的價格購買 9 件商品時出錯:

System.out.println(1.00 - 9 * 0.10);  // Resultado: 0.09999999999999998

即使四捨五入,錯誤仍然存在。
累進計算存在問題,例如以 0.10 到 1.00 的增量價格購買糖果時。

範例 3:
沒錢買糖果時犯的錯誤:

double funds = 1.00;
for (double price = 0.10; funds >= price; price += 0.10) {
    funds -= price;
}
System.out.println(funds);  // Resultado: 0.3999999999999999

解 1:使用 BigDecimal

  • 非常適合財務計算和需要精確度的情況。
  • 避免使用 BigDecimal 的雙重建構函數,最好使用 String 建構函數。

BigDecimal 範例:

BigDecimal funds = new BigDecimal("1.00");
BigDecimal price = new BigDecimal("0.10");
int itemsBought = 0;

while (funds.compareTo(price) >= 0) {
    funds = funds.subtract(price);
    price = price.add(new BigDecimal("0.10"));
    itemsBought++;
}
System.out.println(itemsBought + " items bought. Money left: " + funds);  
// Resultado: 4 items bought. Money left: 0.00

計算現在很精確。

BigDecimal 的缺點:

  • 使用起來不如原始型方便。
  • 速度較慢,特別是對於大量操作。

解 2:使用 int 或 long

  • 為了避免準確度問題,請使用 int 或 long 而不是 double 來以美分為單位進行計算。

int 範例(以分為單位):

int funds = 100;  // 1.00 dólar = 100 centavos
int price = 10;   // 0.10 dólar = 10 centavos
int itemsBought = 0;

while (funds >= price) {
    funds -= price;
    price += 10;
    itemsBought++;
}
System.out.println(itemsBought + " items bought. Money left: " + funds);  
// Resultado: 4 items bought. Money left: 0

計算又快又準。

結論:

  • 不要使用 float 或 double 進行需要精確精確度的計算。
  • 使用 BigDecimal 進行貨幣計算或需要小數精度的情況。
  • 使用 int 或 long 進行不涉及大數的金融計算,以分為單位進行計算。

選擇:

  • 最多 9 位數字,請使用 int。
  • 最多 18 位數字,請使用 long。
  • 對於較大數量,請使用 BigDecimal。
  • 此摘要表明,根據上下文,在 BigDecimal、int 或 long 之間進行選擇可以優化精度和效能。

以上是如果需要準確答案,請避免浮動和雙精度的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn