Reputation: 20306
In the past we have been using Visual Studio's _fpclass to understand if an infinite was positive or negative: http://msdn.microsoft.com/en-us/library/aa246882%28v=vs.60%29.aspx
Passing to std::fpclassify, there's no distinction anymore between positive and negative infinite: http://en.cppreference.com/w/cpp/numeric/math/fpclassify
Can I safely check the sign of infinite with one of the methods here?
Is there a standard sign function (signum, sgn) in C/C++?
Note:
Note 2:
Upvotes: 4
Views: 705
Reputation: 10018
You seem to already know that x
is positive or negative infinity, you just don't know which. In that case, you'd use the same tactic you would if you knew x
were 7
or -7
but didn't know which:
x > 0
There's nothing wrong with that. Of course x > 24
or comparison against any other finite value would work, since positive infinity is larger than all finite values and negative infinity is smaller than all finite values, but comparison with 0
seems like the most readable way to check for the sign.
If you're not sure whether x
is infinity at all then test for it explicitly, as suggested in Fytch's answer:
if (x == std::numeric_limits<double>::infinity()) {
// positive infinity
} else if (x == -std::numeric_limits<double>::infinity()) {
// negative infinity
} else {
// something else
}
Upvotes: 0
Reputation: 1087
For only checking the sign of an infinite value (as stated in the thread title), this code should suffice:
template<typename T>
typename std::enable_if<std::numeric_limits<T>::has_infinity, bool>::type Signed(T const& Value)
{
return Value == -std::numeric_limits<T>::infinity();
}
Edit: If you have access to a C++11 ready compiler, there is also a function provided by the standard library, called std::signbit
in the header <cmath>
. It works for every fundamental floating point type and for every kind of value (so also for infinite and even for NaNs) and should therefore be a more general solution.
Upvotes: 6
Reputation: 136435
You do not really need any special functions to detect infinities and NaNs:
double x = ...;
bool is_nan = x != x;
bool is_finite = !is_nan && x != 2 * x;
bool is_negative = !is_nan && x < 0;
Upvotes: 1