Can you compare floating point values exactly to zero?

后端 未结 8 1405
一生所求
一生所求 2020-12-18 17:57

I know we can\'t compare 2 floating point values using ==. We can only compare they are within some interval of each other. I know

if(val == 0.512)
         


        
8条回答
  •  忘掉有多难
    2020-12-18 18:39

    Use the tolerance / ephsilon approach.

    I just evaluated the following in Java, which mathematically results in zero:

    1.0/5.0 + 1.0/5.0 - 1.0/10.0 - 1.0/10.0 - 1.0/10.0 - 1.0/10.0
    

    and actually got

    2.7755575615628914E-17
    

提交回复
热议问题