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

前端 未结 7 2114
感动是毒
感动是毒 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:45

    The Apache commons-math library provides the nice Precision class (see API Docs), that can compare doubles in different ways:

    Precision.equals(a, b, 0.1); // Tell if |a-b| <= 0.1
    Precision.equals(a, b, 10); // Tell if a and b are less than 10 Ulps apart
    Precision.equalsWithRelativeTolerance(a, b, 0.05); // Tell if a and b are less than 5% apart
    

提交回复
热议问题