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

Approximate equality is defined in terms of the absolute difference: if an absolute difference does not exceed a certain, presumably small, number, then you can say that the values you are comparing are "close enough".

double diff = Math.abs(actual - expected);
if (diff < 1E-7) {
    // Numbers are close enough
}

You must be very careful to not confuse "close enough" end "equals", because the two are fundamentally different: equality is transitive (i.e. a==b and b==c together imply that a==c), while "close enough" is not transitive.


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.


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

Where eps is measure of equality.