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

后端 未结 9 963
刺人心
刺人心 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 03:14

    You do need to exercise some care.

    1.0 + 2.0 == 3.0
    

    is true because integers are exactly representable.

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

    if b == c.

    b / 3.0 == 10.0 / 3.0
    

    if b == 10.0 which is what I think you meant.

    The last two examples compare two different instances of the same calculation. When you have different calculations with non representable numbers then exact equality testing fails.

    If you are testing the results of a calculation that is subject to floating point approximation then equality testing should be done up to a tolerance.

    Do you have any specific real world examples? I think you will find that it is rare to want to test equality with floating point.

    0 讨论(0)
  • 2020-12-17 03:15

    Float wrapper class's compare method can be used to compare two float values.

    Float.compare(float1,float2)==0
    

    It will compare integer bits corresponding to each float object.

    0 讨论(0)
  • 2020-12-17 03:17

    b / 3 != 10 / 3 - if b is a floating point variable like b = 10.0f, so b / 3 is 3.3333, while 10 / 3 is integer division, so is equal to 3.

    If b == c, then Math.sqrt(b) == Math.sqrt(c) - this is because the sqrt function returns double anyways.

    In general, you shouldn't be comparing doubles/floats for equation, because they are floating point numbers so you might get errors. You almost always want to compare them with a given precision, i.e.:

    b - c < 0.000001

    0 讨论(0)
提交回复
热议问题