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.
double
s are not perfectly accurate, and not every decimal can be perfectly represented as adouble
(see this). For all practical purposes,-3.3306690738754696E-16
is0
*. However, if you need more precision, useBigDecimal
. Keep in mind that this alternative will not be nearly as efficient as using primitivedouble
s. 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".
double
values cannot represent all values precisely and this is such an example. You can useBigDecimal
instead:Output: