Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare that sequence of doubles are all "approximately equal" in Java?

Tags:

I have a method in java that returns a double number and I want to compare every double number that is returned every time I call the method(say 5 times), so that I can conclude that the number returned is almost the same every time.

How can I do this?

like image 946
FranXh Avatar asked Feb 01 '12 03:02

FranXh


People also ask

Can you use == to compare doubles 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.

Why use .equals instead of == Java?

== should be used during reference comparison. == checks if both references points to same location or not. equals() method should be used for content comparison. equals() method evaluates the content to check the equality.

How do you compare double numbers?

To compare two floating point or double values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.


2 Answers

public static boolean almostEqual(double a, double b, double eps){     return Math.abs(a-b)<eps; } 

Where eps is measure of equality.

like image 196
Ano Avatar answered Sep 19 '22 04:09

Ano


You must first decide what "almost the same" means. For example, there's a method in java.lang.Math called ulp() which, given a double, returns the distance between that double and the next; i.e., the smallest possible difference between that number and any other. You might simply compare the difference between the two doubles and the result of calling that method.

On the other hand, maybe you want two numbers to just be within 1% of eachother. In that case, do the same computation, but use the first number multiplied by 0.01 instead of ulp() as the largest acceptable distance.

like image 39
Ernest Friedman-Hill Avatar answered Sep 17 '22 04:09

Ernest Friedman-Hill