poe*_*lot 3 java floating-point bigdecimal ieee-754 single-precision
根据几个浮点计算器以及我下面的代码,以下 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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
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
Run Code Online (Sandbox Code Playgroud)
没有实际的精度损失;问题是您对双打如何转换为String(例如打印时)的错误期望。
m 或 a 的小数部分必须打印多少位?必须至少有一个数字来表示小数部分,并且超过这个数字,但只有尽可能多的数字,以唯一地将参数值与双精度类型的相邻值区分开来。也就是说,假设 x 是由此方法为有限非零参数 d 生成的十进制表示所表示的精确数学值。那么 d 必须是最接近 x 的双精度值;或者如果两个 double 值同样接近 x,则 d 必须是其中之一,并且 d 的有效数的最低有效位必须为 0。
因此,当 adouble被打印时,它只打印了足够的数字来唯一标识该double值,而不是将精确值描述为实数所需的位数。
如果你想double用所有可能的数字获得 a 的精确值,new BigDecimal(theDouble).toPlainString()就是你怎么做的 - 正如你所演示的,它会得到正确的结果。