Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 828
elzell Avatar asked Oct 15 '18 13:10

elzell


People also ask

Can I use infinity in C?

C allows us to define INFINITY as positive INFINITY or negative INFINITY .

What is inf in C?

Inf means infinity, and is the result of dividing a positive number by zero -- e.g., 1/0 → Inf. or computing a number larger than 1.796E308 (the largest number that your computer can represent in 64 bits) -- e.g. 1E307 * 100 → Inf.

What is NaN and inf in C?

In comparison operations, positive infinity is larger than all values except itself and NaN, and negative infinity is smaller than all values except itself and NaN. NaN is unordered: it is not equal to, greater than, or less than anything, including itself.

Is infinity a NaN?

In floating-point calculations, NaN is not the same as infinity, although both are typically handled as special cases in floating-point representations of real numbers as well as in floating-point operations.


1 Answers

(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.

like image 183
Blaze Avatar answered Sep 16 '22 14:09

Blaze