[英]After converting bits to Double, how to store actual float/double value without using BigDecimal?
根據幾個浮點計算器以及我下面的代碼,以下 32 位00111111010000000100000110001001的實際浮點值為 (0.750999987125396728515625)。 由於它是實際的 Float 值,我應該認為將其存儲在 Double 或 Float 中會保留精度和精確值,只要(1)不執行算術(2)使用實際值和(3)值是沒有被貶低。 那么為什么實際值與 (0.7509999871253967) 的強制轉換(示例 1)和文字(示例 2)值不同?
我以這個計算器為例: https://www.h-schmidt.net/FloatConverter/IEEE754.html
import java.math.BigInteger;
import java.math.BigDecimal;
public class MyClass {
public static void main(String args[]) {
int myInteger = new BigInteger("00111111010000000100000110001001", 2).intValue();
Double myDouble = (double) Float.intBitsToFloat(myInteger);
String myBidDecimal = new BigDecimal(myDouble).toPlainString();
System.out.println(" bits converted to integer: 00111111010000000100000110001001 = " + myInteger);
System.out.println(" integer converted to double: " + myDouble);
System.out.println(" double converted to BigDecimal: " + myBidDecimal);
Double myDouble2 = 0.750999987125396728515625;
String myBidDecimal2 = new BigDecimal(myDouble2).toPlainString();
System.out.println("");
System.out.println(" Ignore the binary string: ");
System.out.println(" double from literal: " + myDouble2);
System.out.println(" double converted to BigDecimal: " + myBidDecimal2);
}
}
這是 output:
bits converted to integer: 00111111010000000100000110001001 = 1061175689
integer converted to double: 0.7509999871253967
double converted to BigDecimal: 0.750999987125396728515625
Ignore the binary string:
double from literal: 0.7509999871253967
double converted to BigDecimal: 0.750999987125396728515625
沒有實際的精度損失; 問題是您對如何將雙打轉換為String
(例如打印時)的錯誤期望。
m 或 a 的小數部分必須打印多少位? 必須至少有一個數字來表示小數部分,除此之外,必須有盡可能多的數字,但僅能將參數值與相鄰的 double 類型值區分開來。 也就是說,假設 x 是由該方法為有限非零參數 d 生成的十進制表示所表示的精確數學值。 那么 d 必須是最接近 x 的 double 值; 或者如果兩個雙精度值同樣接近 x,則 d 必須是其中之一,並且 d 的有效位的最低有效位必須為 0。
因此,當一個double
被打印時,它只打印了足夠的數字來唯一標識該double
值,而不是用將精確值描述為實數所需的位數。
如果您想獲得具有所有可能數字的double
精度值,那么new BigDecimal(theDouble).toPlainString()
就是您的方法 - 而且,正如您所演示的,它會得到正確的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.