我想了解 Java double
类型如何将其值存储在 Java 的内存中。
当我运行以下代码时,我得到了意外的输出:
public static void main(String[] args) {
float a = 1.5f;
float b= 0.5f;
double c= 1.5;
double d = 0.5;
float a1 = 1.4f;
float b1= 0.5f;
double c1= 1.4;
double d1 = 0.5;
System.out.println(" a- b is " + (a-b));
System.out.println(" c- d is " + (c-d));
System.out.println("a1-b1 is " + (a1-b1));
System.out.println("c1-d1 is " + (c1-d1));
输出:
a- b is 1.0 c- d is 1.0 a1-b1 is 0.9 c1-d1 is 0.8999999999999999
为什么c1-d1
不等于0.9
?
我也尝试了其他不同的值,但有时它会返回预期结果,有时则不会。
最佳答案
虽然您可能听说过舍入误差,但您可能想知道为什么会出现舍入误差。
float a1 = 1.4f;
float b1 = 0.5f;
double c1 = 1.4;
double d1 = 0.5;
System.out.println(new BigDecimal(a1) + " - " + new BigDecimal(b1) + " is " +
new BigDecimal(a1).subtract(new BigDecimal(b1)) + " or as a float is " + (a1 - b1));
System.out.println(new BigDecimal(c1) + " - " + new BigDecimal(d1) + " is " +
new BigDecimal(c1).subtract(new BigDecimal(d1)) + " or as a double is " + (c1 - d1));
打印
1.39999997615814208984375 - 0.5 is 0.89999997615814208984375 or as a float is 0.9
1.399999999999999911182158029987476766109466552734375 - 0.5 is
0.899999999999999911182158029987476766109466552734375
or as a double is 0.8999999999999999
如您所见,float
和 double
都不能准确表示这些值,并且在打印 float 或 double 时,会进行一些舍入以向您隐藏这一点。在这个 float 的例子中,四舍五入到小数点后 7 位得到你期望的数字。对于 16 位精度的 double,舍入误差是可见的。
正如@Eric Postpischil 所说,float
或double
运算是否有舍入误差完全取决于所使用的值。在这种情况下,即使表示的值比 double 值离 0.9 更远, float 似乎更准确。
简而言之:如果您要使用float
或double
,您应该使用合理的舍入策略。如果您不能这样做,请使用 BigDecimal。
System.out.printf("a1 - b1 is %.2f%n", (a1 - b1));
System.out.printf("c1 - d1 is %.2f%n", (c1 - d1));
打印
a1 - b1 is 0.90
c1 - d1 is 0.90
当您打印 float 或 double 时,它假定最接近的短十进制值是您真正想要的值。即在 0.5 ulp 以内。
例如
double d = 1.4 - 0.5;
float f = d;
System.out.println("d = " + d + " f = " + f);
打印
d = 0.8999999999999999 f = 0.9
关于java - 双原始类型数据的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13088648/