Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Double Comparison [duplicate]

Tags:

java

double

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.

like image 813
DD. Avatar asked Jul 09 '12 07:07

DD.


People also ask

Can you use == to compare double in Java?

Using the == Operator As a result, we can't have an exact representation of most double values in our computers. They must be rounded to be saved. In that case, comparing both values with the == operator would produce a wrong result.

What is double == in Java?

equals() is a built-in function in java that compares this object to the specified object. The result is true if and only if the argument is not null and is a Double object that contains the same double value as this object. It returns false if both the objects are not same.

Can we use .equals for double?

@YoTengoUnLCD Yes, exactly, and it works the same way with Double . == compares references where equals compares value.


2 Answers

Guava has DoubleMath.fuzzyCompare().

like image 167
Joachim Sauer Avatar answered Sep 29 '22 11:09

Joachim Sauer


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

like image 24
Lucian Enache Avatar answered Sep 29 '22 11:09

Lucian Enache