Can you safely check the infinity sign?

We've used Visual Studio's _fpclass in the past to figure out if infinity was positive or negative: http://msdn.microsoft.com/en-us/library/aa246882%28v=vs.60%29.aspx

Moving on to std :: fpclassify, there is no difference between positive and negative infinite: http://en.cppreference.com/w/cpp/numeric/math/fpclassify

Is it safe to check the infinity sign with one of the methods here?
Is there a standard sign function (signum, sgn) in C / C ++?

Note:

Note 2:

  • C ++ 11 is applicable
+3


source to share


3 answers


To test only the sign of an infinite value (as stated in the stream header) this code should be sufficient:

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 ready-made C ++ 11 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 value type (also infinite and even NaN) and therefore should be a more general solution.

+6


source


You don't really need special functions for defining 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;

      

+2


source


The following will check the sign of something:

bool is_positive = std::to_string(x)[0] != '-';

      

0


source







All Articles