3
votes

Floating-point equality comparison sometimes has weird edge cases e.g. two NaN values compare as not equal even if they are identical bit patterns.

Can it be assumed, however, that inequality is always the inverse of equality? That is, assuming standard IEEE 64-bit floating-point numbers as implemented on mainstream architectures such as x64, exactly one of a == b and a != b will always be true regardless of what bit patterns are present?

2

2 Answers

4
votes

Yes, this will be always true, there are no number interpretations of bit patterns for which the operator == will not return the exact opposite for !=.

There are exceptions for bit patterns which compare as equal for different bit patterns (negative zero 0x80... is equal to zero 0x00...) or same bit pattern compare as unequal (NaNs) as you already mentioned, but != is always the inversion of ==.

2
votes

One must be careful about what relation is being tested. There are different tests for “Do x and y have different values?” and “Is x not equal to y?”

If x or y is a NaN, or both, then it is false that they have different values (because at least one of them does not have any value at all), but it is true that there is no equality.

The C operator != asks about “not equal”, so it answers the latter question. And because it asks about “not equal”, it is the logical negation of “equal”.

Some languages provide a way to ask the former question.