Getting wrong answer in double arithmetic in Java [duplicate]

一世执手 提交于 2019-12-11 04:35:48

问题


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.


回答1:


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



回答2:


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".



来源:https://stackoverflow.com/questions/14187997/getting-wrong-answer-in-double-arithmetic-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!