Let's analyze this part:
if(Double.compare(a, b) == 0)
By looking at the documentation of Double.compare
, a possible implementation could be the following one (obviously it will be a more optimized one, but that's for the sake of the discussion):
return a == b ? 0 : (a < b ? -1 : +1);
Then, you have another comparison, so it becomes:
if((a == b ? 0 : (a < b ? -1 : +1)) == 0)
In the other case, you rely on a simple comparison using ==
, that is:
if(a == b)
That said, in terms of accuracy I guess the result is the same, for the underlying representation of a double
does not change and the comparison with 0 does not seem to affect the accuracy.
Which is the best?
Well, from the example above, I'd say the simpler one for you directly compare the values and you are interested only in equality, even though it's unlikely that you are facing with a problem which will benefit from choosing the best way for such a comparison.
Anyway, the approach using Double.compare
is more suitable for those cases when you are not only interested in equality, but also in the concepts of greater than and/or less than.