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

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

    You could use Guava and DoubleMath#fuzzyEquals method (since version 13.0):

    public static boolean fuzzyEquals(double a, double b, double tolerance)
    

    Returns true if a and b are within tolerance of each other. Technically speaking, this is equivalent to Math.abs(a - b) <= tolerance || Double.valueOf(a).equals(Double.valueOf(b)).

    Notable special cases include:

    Link to docs: https://google.github.io/guava/releases/17.0/api/docs/com/google/common/math/DoubleMath.html

提交回复
热议问题