Search code examples
cfloating-pointinfinity

Why does comparison of floating-point to infinity work?


As anyone knowledgeable enough will know, you cannot compare two floating-point numbers with simple logic operators and expect a logical result.

Why then, does a logical EQUAL TO comparison to INFINITY always return true when the number is, in fact, INFINITY?

PS: I tried the same comparison with NAN, but it seems only INFINITY can be reliably detected as being equal to another number of the same value.

(Edit) Here is my implementation's (GCC) definition of INFINITY and NAN:

#  define INFINITY (__builtin_inff ())
#  define NAN (__builtin_nanf (""))

Solution

  • As anyone knowledgeable enough will know, you cannot compare two floating-point numbers with simple logic operators and expect a logical result.

    This has no basis in the IEEE 754 standard or any other specification of floating-point behavior I am aware of. It is an unfortunately common misstatement of floating-point arithmetic.

    The fact is that comparison for equality is a perfect operation in floating-point: It produces true if and only if the two operands represent the same number. There is never any error in a comparison for equality.

    Another misstatement is that floating-point numbers approximate real numbers. Per IEEE 754, each floating-point value other than NaN represents one number, and it represents that number exactly.

    The fact is that floating-point numbers are exact while floating-point operations approximate real arithmetic; correctly-rounded operations produce the nearest representable value (nearest in any direction or in a selected direction, with various rules for ties).

    This distinction is critical for understanding, analyzing, designing, and writing proofs about floating-point arithmetic.

    Why then, does a logical EQUAL TO comparison to INFINITY always return true when the number is, in fact, INFINITY?

    As stated above, comparison for equality produces true if and only if its operands represent the same number. If x is infinity, then x == INFINITY returns true. If x is three, then x == 3 returns true.

    People sometimes run into trouble when they do not understand what value is in a number. For example, in float x = 3.3;, people sometimes do not realize that C converts the double 3.3 to float, and therefore x does not contain the same value as 3.3. This is because the conversion operation approximates its results, not because the value of x is anything other than its specific assigned value.

    I tried the same comparison with NAN,…

    A NaN is Not a Number, so, in a comparison for equality, it never satisfies “the two operands represent the same number”, so the comparison produces false.