久久久久久久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(使用線程逐塊處理文件)
主站蜘蛛池模板: 午夜免费av | 欧美成人a | 狠狠骚| 亚洲瑟瑟 | 成人不卡一区二区 | 日韩有码在线播放 | 国产激情综合五月久久 | 成人午夜性成交 | 国产综合网址 | 久久久人成影片一区二区三区 | 久久久久久久久久爱 | 成人在线精品 | 亚洲韩国精品 | 亚洲激情第一页 | 欧美日韩高清在线观看 | 亚洲精品视频久久 | 国产区视频在线观看 | 91精品国产综合久久精品 | 天天色图 | 天堂一区 | 日韩一区二区在线免费观看 | www.日日操| 国产精品久久久久久久久免费相片 | 久久久蜜桃一区二区人 | 国产一区二区自拍 | 国产98色在线 | 日韩 | 精品二区| 欧美日韩福利视频 | 亚洲综合视频 | 天天综合久久 | 黄色成人免费在线观看 | 久草福利| 欧美久久一区 | 欧美日韩在线一区二区三区 | 日韩在线不卡视频 | 国产乱码精品一区二区三区av | 亚洲视频精品在线 | 97超碰站 | 国产亚洲一区二区三区 | 91精品久久久久久久久久 | 国产精品99久久久久久动医院 |