根据几个浮点计算器以及下面的代码,以下32位00111111010000000100000110001001的实际浮点值为(0.75099998712396728515625)。由于它是实际的浮点数,所以我认为,如果(1)不执行任何算术运算,(2)使用实际值,(3)该值不是向下浇铸的,那么将它存储在双值或浮点数中就能保持精确和精确的值。那么,为什么实际值与铸(示例1)和文字(示例2)值(0.7509999871253967)不同呢?
我以这个计算器为例: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);
}
}这是输出:
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发布于 2020-06-05 22:31:47
不存在精度的实际损失;问题是您对双打如何转换为String (例如打印时)的错误期望。
来自the documentation of Double.toString
对于m或a的小数部分必须打印多少位数?必须至少有一个数字来表示小数部分,除此之外,还必须有尽可能多的数字,但只有尽可能多的数字才能唯一地区分参数值和类型为double的相邻值。即,假设x是用这种方法对有限的非零参数d生成的十进制表示所表示的精确数学值,那么d必须是离x最近的双值;或者如果两个双值与x相等,那么d必须是其中之一,d的最小意义位必须是0。
因此,当一个double被打印出来时,它只使用足够的数字来唯一地标识这个double值,而不是用将精确的值描述为实数所需的数字数。
如果你想用所有可能的数字得到一个double的精确值,那么new BigDecimal(theDouble).toPlainString()就是你怎么做的--正如你所演示的,它得到了正确的结果。
https://stackoverflow.com/questions/62224816
复制相似问题