Can you compare floating point values exactly to zero?

后端 未结 8 1404
一生所求
一生所求 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:44

    Because zero does have an exact representation, it is possible for a value to compare == to zero. If the variable you are testing was set by an assignment, or from a value typed in (like getVal in your example?), it could easily be zero. But if it was the result of a calculation, the chances of it being exactly zero are very small. This is made worse because ordinary decimal fractions like 0.2 do not have an exact representation in floating point. That's why it's best to use epsilon.

提交回复
热议问题