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

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

    What does it mean for two doubles to be "approximately equal?" It means that the doubles are within some tolerance of each other. The size of that tolerance, and whether that tolerance is expressed as an absolute number or as a percentage of the two doubles, depends on your application.

    For instance, two photos displayed on a photo viewer have approximately the same width in inches if they take up the same number of pixels on the screen, so your tolerance will be an absolute number calculated based on pixel size for your screen. On the other hand, two financial firms' profits are probably "approximately equal" if they are within 0.1% of each other. These are just hypothetical examples, but the point is that it depends on your application.

    Now for some implementation. Let's say your application calls for an absolute tolerance. Then you can use

    private static final double TOLERANCE = 0.00001;
    
    public static boolean approxEqual(final double d1, final double d2) {
        return Math.abs(d1 - d2) < TOLERANCE;
    }
    

    to compare two doubles, and use

    approxEqual(d1, d2) && approxEqual(d1, d3) && approxEqual(d1, d4) && approxEqual(d1, d5)
    

    to compare five doubles.

提交回复
热议问题