簡體   English   中英

在不損失精度的情況下安全地將“float”轉換為“double”

[英]Safely convert `float` to `double` without loss of precision

我有以下頭部刮刀,在jshell 11.0.1217.0.1中演示

jshell> 13.9f
$1 ==> 13.9

jshell> 13.9
$2 ==> 13.9

jshell> (double) 13.9f
$3 ==> 13.899999618530273

同樣的事情發生在兩個版本的簡單編譯的 class 中

strictfp public class Test {

    public strictfp static void main(String[] args) {
        System.out.format("%s%n", (double) 13.9f);
        System.out.format("%s%n", 13.9f);
    }

}
╰─➤  java Test      
13.899999618530273
13.9

雖然 17 警告不再需要strictfp

warning: [strictfp] as of release 17, all floating-point expressions are evaluated strictly and 'strictfp' is not required

JLS在第 5.1.2 節中說明了這一點

A widening primitive conversion does not lose information about the overall
magnitude of a numeric value in the following cases, where the numeric value is
preserved exactly:
• from an integral type to another integral type
• from byte, short, or char to a floating-point type
• from int to double
• from float to double

在 14 中,它在項目符號列表之后包含以下內容

A widening primitive conversion from float to double that is not strictfp may
lose information about the overall magnitude of the converted value.

根據我的閱讀,這是實施中的錯誤嗎? 我發現執行此轉換的唯一可靠方法是Double.parseDouble(Float.toString(13.9f))

根據我的閱讀,這是實施中的錯誤嗎?

不,這是您期望中的錯誤。 您看到的double精度值與float值完全相同。 精確值為 13.8999996185302734375。

與“最接近 13.9 的double精度值”不同,后者是 13.9000000000000003552713678800500929355621337890625。

您將值 13.8999996185302734375 分配給double精度值,然后打印字符串表示形式 - 即 13.899999618530273,因為這足以將其與其他double精度值完全區分開來。 如果要打印 13.9,那是一個錯誤,因為有一個更接近 13.9 的double精度值,即 13.90000000000000003552713678800500929355621337890625。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM