oliver
oliver

Reputation: 6781

What's the recommended workaround if numeric_limits<double>::has_infinity is false?

I need to check a double value for infinity in a C++ app on Linux. On most platforms this works by comparing with std::numeric_limits<double>::infinity(). However, on some old platforms (RedHat 9 for example, with gcc 3.2.2) this is not available, and std::numeric_limits<double>::has_infinity is false there.

What workaround would you recommend for those platforms?

Upvotes: 2

Views: 3436

Answers (3)

oliver
oliver

Reputation: 6781

Ok, I have now resorted to using the INFINITY and NAN macros on that particular machine - seems to work fine. They come from math.h.

Upvotes: 1

j_random_hacker
j_random_hacker

Reputation: 51256

If you're using IEEE 754 arithmetic, as you almost certainly are, infinities are well defined values and have defined outcomes for all arithmetic operations. In particular,

infinity - infinity = NaN

Positive and negative infinity and NaN values are the only values for which this is true. NaNs are special "not-a-number" values used to indicate domain errors of functions, e.g. sqrt(-1). Also:

NaN != NaN

NaNs are the only values for which this is true.

Therefore:

bool is_infinite(double x) {
    double y = x - x;
    return x == x && y != y;
}

will return true if and only if x is either positive or negative infinity. Add a test for x > 0 if you only want to check for positive infinity.

Upvotes: 3

Andrei Krotkov
Andrei Krotkov

Reputation: 5694

For most cases, std::numeric_limits::max() can be a valid replacement for std::numeric_limits::infinity().

You would have to be more careful about using it, however. With overflows I believe you would have to manually detect the overflow and set the result to the max explicitly if an overflow is detected.

Upvotes: 1

Related Questions