Comparing IEEE floats and doubles for equality

前端 未结 15 2160
南方客
南方客 2020-11-30 06:00

What is the best method for comparing IEEE floats and doubles for equality? I have heard of several methods, but I wanted to see what the community thought.

相关标签:
15条回答
  • 2020-11-30 07:04

    Oh dear lord please don't interpret the float bits as ints unless you're running on a P6 or earlier.

    Even if it causes it to copy from vector registers to integer registers via memory, and even if it stalls the pipeline, it's the best way to do it that I've come across, insofar as it provides the most robust comparisons even in the face of floating point errors.

    i.e. it is a price worth paying.

    0 讨论(0)
  • 2020-11-30 07:04

    It rather depends on what you are doing with them. A fixed-point type with the same range as an IEEE float would be many many times slower (and many times larger).

    Okay, but if I want a infinitesimally small bit-resolution then it's back to my original point: == and != have no meaning in the context of such a problem.

    An int lets me express ~10^9 values (regardless of the range) which seems like enough for any situation where I would care about two of them being equal. And if that's not enough, use a 64-bit OS and you've got about 10^19 distinct values.

    I can express values a range of 0 to 10^200 (for example) in an int, it is just the bit-resolution that suffers (resolution would be greater than 1, but, again, no application has that sort of range as well as that sort of resolution).

    To summarize, I think in all cases one either is representing a continuum of values, in which case != and == are irrelevant, or one is representing a fixed set of values, which can be mapped to an int (or a another fixed-precision type).

    0 讨论(0)
  • 2020-11-30 07:04

    Oh dear lord please don't interpret the float bits as ints unless you're running on a P6 or earlier.

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