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

前端 未结 7 2127
感动是毒
感动是毒 2021-02-07 02:22

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

7条回答
  •  攒了一身酷
    2021-02-07 02:52

    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.

提交回复
热议问题