Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you safely check the sign of infinite?

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:

  • Independently if fastmath is enabled
  • In a portable way

Note 2:

  • C++11 is applicable
like image 352
Antonio Avatar asked Feb 13 '23 00:02

Antonio


2 Answers

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.

like image 186
Fytch Avatar answered Feb 14 '23 15:02

Fytch


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;
like image 30
Maxim Egorushkin Avatar answered Feb 14 '23 15:02

Maxim Egorushkin