How dangerous is it to compare floating point values?

前端 未结 11 824
囚心锁ツ
囚心锁ツ 2020-11-21 06:44

I know UIKit uses CGFloat because of the resolution independent coordinate system.

But every time I want to check if for example fram

11条回答
  •  一生所求
    2020-11-21 07:11

    Since 0 is exactly representable as an IEEE754 floating-point number (or using any other implementation of f-p numbers I've ever worked with) comparison with 0 is probably safe. You might get bitten, however, if your program computes a value (such as theView.frame.origin.x) which you have reason to believe ought to be 0 but which your computation cannot guarantee to be 0.

    To clarify a little, a computation such as :

    areal = 0.0
    

    will (unless your language or system is broken) create a value such that (areal==0.0) returns true but another computation such as

    areal = 1.386 - 2.1*(0.66)
    

    may not.

    If you can assure yourself that your computations produce values which are 0 (and not just that they produce values which ought to be 0) then you can go ahead and compare f-p values with 0. If you can't assure yourself to the required degree, best stick to the usual approach of 'toleranced equality'.

    In the worst cases the careless comparison of f-p values can be extremely dangerous: think avionics, weapons-guidance, power-plant operations, vehicle navigation, almost any application in which computation meets the real world.

    For Angry Birds, not so dangerous.

提交回复
热议问题