Floating Point, how much can I trust less than / greater than comparisons?

前端 未结 5 1363
死守一世寂寞
死守一世寂寞 2021-02-19 04:08

Let\'s say I have two floating point numbers, and I want to compare them. If one is greater than the other, the program should take one fork. If the opposite is true, it should

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-19 04:49

    If you can guarantee that a and b are not NaNs or infinities, then you can just do:

    if (a

    The set of all floating point values except for infinities and NaNs comprise a total ordering (with a glitch with two representations of zero, but that shouldn't matter for you), which is not unlike working with normal set of integers — the only difference is that the magnitude of intervals between subsequent values is not constant, like it is with integers.

    In fact, the IEEE 754 has been designed so that comparisons of non-NaN non-infinity values of the same sign can be done with the same operations as normal integers (again, with a glitch with zero). So, in this specific case, you can think of these numbers as of “better integers”.

提交回复
热议问题