Is it safe when compare 2 float/double directly in Java?

后端 未结 9 1053
刺人心
刺人心 2020-12-17 02:30

Is it safe if I use comparision like this (a is int, b and c is float/double):

a == b
b == c

It may hear ridiculous, but in my old programi

9条回答
  •  感动是毒
    2020-12-17 02:59

    == comparison is not particularly safe for doubles/floats in basically any language. An epsilon comparison method (where you check that the difference between two floats is reasonably small) is your best bet.

    For:

    Math.sqrt(b) == Math.sqrt(c)
    

    I'm not sure why you wouldn't just compare b and c, but an epsilon comparison would work here too.

    For:

    b / 3 == 10 / 3
    

    Since 10/3 = 3 because of integer division, this will not necessarily give the results you're looking for. You could use 10.0 / 3, though i'm still not sure why you wouldn't just compare b and 10 (using the epsilon comparison method in either case).

提交回复
热议问题