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

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

    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.

提交回复
热议问题