[英]Safely convert `float` to `double` without loss of precision
我有以下頭部刮刀,在jshell
11.0.12
和17.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.