久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

如何避免 Java 中的浮點數或雙精度數的浮點精度

How to avoid floating point precision errors with floats or doubles in Java?(如何避免 Java 中的浮點數或雙精度數的浮點精度錯誤?)
本文介紹了如何避免 Java 中的浮點數或雙精度數的浮點精度錯誤?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

我有一個非常煩人的問題,即 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 精確表示為 floatdouble.由于這種表示錯誤,結果與您的預期略有不同.

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模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

How to wrap text around components in a JTextPane?(如何在 JTextPane 中的組件周圍環繞文本?)
MyBatis, how to get the auto generated key of an insert? [MySql](MyBatis,如何獲取插入的自動生成密鑰?[MySql])
Inserting to Oracle Nested Table in Java(在 Java 中插入 Oracle 嵌套表)
Java: How to insert CLOB into oracle database(Java:如何將 CLOB 插入 oracle 數據庫)
Why does Spring-data-jdbc not save my Car object?(為什么 Spring-data-jdbc 不保存我的 Car 對象?)
Use threading to process file chunk by chunk(使用線程逐塊處理文件)
主站蜘蛛池模板: 诱人的大乳奶3做爰 | 久久精品毛片 | 午夜久久久| 国产资源在线观看 | 欧美日韩免费在线观看 | 九九国产视频 | 成人午夜激情视频 | 夜夜嗨av一区二区三区网页 | www国产精品| 久热中文字幕 | 一区二区三区四区视频在线观看 | 日韩精品在线一区二区 | 天堂中文av| 亚洲免费观看视频 | 国产福利91精品一区二区三区 | 国产精品手机在线观看 | 中文字幕免费 | 一区二区三区在线免费 | 免费视频一区 | 亚洲乱淫 | 超碰91在线 | 午夜一级片 | 日韩欧美不卡 | 一区二区三区四区精品 | 中文字幕在线免费看 | 精品一区在线播放 | 黄色福利| 精品一区二区在线播放 | 性av在线 | 91精品国产乱码久久久久久 | 中文字幕av久久爽一区 | 欧美理伦 | 色综合天天综合网国产成人网 | 欧美精品99久久久 | 免费看黄色小视频 | 亚洲色综合 | av网址在线免费观看 | 亚洲综合五月 | av色婷婷 | 欧美日韩综合 | 久久国产99|