Getting wrong answer in double arithmetic in Java

2019-02-28 16:40发布

Possible Duplicate:
Double calculation producing odd result

I'm writing a program in Java that deals with a lot of double arithmetic. I eventually get to the point where I need to add 0.6666666666666666 and -0.666666666666667. However, the answer that I get is -3.3306690738754696E-16.

In other words,

double d1 = 0.6666666666666666;
double d2 = -0.666666666666667;
System.out.println(d1 + d2);

prints out "-3.3306690738754696E-16". Why is this happening?

Thank you in advance.

2条回答
地球回转人心会变
2楼-- · 2019-02-28 17:07

doubles are not perfectly accurate, and not every decimal can be perfectly represented as a double (see this). For all practical purposes, -3.3306690738754696E-16 is 0 *. However, if you need more precision, use BigDecimal. Keep in mind that this alternative will not be nearly as efficient as using primitive doubles. It's up to you to decide if you need this level of accuracy and to make a choice accordingly.

*: Evidently, that number is not exactly zero, but for the majority of real-world calculations and computations, a value that small would be inconsiderable. In meters, this value is smaller than the diameter of protons and neutrons - i.e. very very small. That's what I mean by "for all practical purposes".

查看更多
神经病院院长
3楼-- · 2019-02-28 17:13

double values cannot represent all values precisely and this is such an example. You can use BigDecimal instead:

BigDecimal bd1 = new BigDecimal("0.6666666666666666");
BigDecimal bd2 = new BigDecimal("-0.666666666666667");
System.out.println(bd1.add(bd2));

Output:

-4E-16
查看更多
登录 后发表回答