Java Double Comparison [duplicate]

2019-02-12 07:31发布

问题:

This question already has an answer here:

  • comparing float/double values using == operator 9 answers

Are there any java libraries for doing double comparison? e.g.

public static boolean greaterThanOrEqual(double a, double b, double epsilon){
     return a - b > -epsilon;
}

Every project I start I end up re-implementing this and copy-pasting code and test.

NB a good example of why its better to use 3rd party JARs is that IBM recommend the following:

"If you don't know the scale of the underlying measurements, using the test "abs(a/b - 1) < epsilon" is likely to be more robust than simply comparing the difference"

I doubt many people would have thought of this and illustrates that even simple code can be sub-optimal.

回答1:

Guava has DoubleMath.fuzzyCompare().



回答2:

In the standard Java library there are no methods to handle your problem actually I suggest you to follow Joachim's link and use that library which is quite good for your needs, even though my suggestion would be to create an utils library in which you could add frequently used methods as the one you've stated in your question, as for different implementations of your problem you should consider looking into this :

Java double comparison epsilon

Feel free to ask out any other ambiguities



回答3:

You should abstain from any library that uses the naive "maximum absolute difference" approach (like Guava). As detailed in the Bruce Dawson's excellent article Comparing Floating Point Numbers, 2012 edition, it is highly error-prone as it only works for a very limited range of values. A much more robust approach is to use relative differences or ULPs for approximate comparisons.

The only library I know of that does implement a correct approximate comparison algorithm is apache.common.math.



标签: java double