Search code examples
c++floating-pointinfinity

Compare infinity with infinity in C++


Suppose I have two variables which are both set to infinity

double l = std::numeric_limits<double>::infinity();
double r = std::numeric_limits<double>::infinity();

At another point in the code, I have a comparison of these two variables

if (l < r) {}

Is the result of this comparison properly defined in the library? (Within the logic of my program, I would expect the result to be false.)


Solution

  • (Within the logic of my program, I would expect the result to be false.)

    According to this:

    In comparison operations, positive infinity is larger than all values except itself and NaN

    So you are indeed correct.

    Note that this might not be valid if your compiler uses a different standard than IEEE 754, so make sure that std::numeric_limits<double>::is_iec559; returns true when in doubt.