Can you compare floating point values exactly to zero?

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

    For comparison with err all you need to is.

    // compare a and b with an ERR error.
    if (Math.abs(a - b) <= ERR)
    

    To compare with 0

    // compare a and 0 with an ERR error.
    if (Math.abs(a) <= ERR)
    
    0 讨论(0)
  • 2020-12-18 18:58

    I would still recommend following the tolerance idiom and not compare to zero exactly.

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