Dear all,
is there in c++ an analogous of Matlab NaN values?
In Matlab NaN is a special value that you can assign
to double variables and use it for example to mark special position
in vectors (for example imagine a polygon made of two disjoint regions,
you can separate the two regions using NaN),
it is the value returned when making a 0/0 division and so on
Is there any such special value in c++? Googling I think there is
and that I have to use a<limit> library, but I couldn't really
find more information, especially concerning the efficiency of such a library.
The C++ standard does not require a floating point representation that
does have NaN, but usually it will be by default be IEEE 754, which does
support NaN and Infinity values.
Even the C++03 standard let you test for the presence of NaN support, like
typedef std::numeric_limits<double> Fp;
std::cout << std::boolalpha;
std::cout << "Has quiet Nan: " << Fp::has_quiet_NaN << "\n";
std::cout << "Has signaling NaN: " << Fp::has_signaling_NaN << "\n";
And it let you test for IEEE 754 conformance:
std::cout << "Is IEEE 754: " << Fp::is_iec559 << "\n";
The main problem with that was and is that implementations such as
Visual C++ and the GNU toolchain let the user choose optimizations where
the floating point behavior is decidedly not IEEE 754 conforming.
So you can't even reliably test for IEEE 754.
You just have to document requirements very cleary, e.g. "this library
requires IEEE 754 conformance, don't use e.g. -fastmath option".
And in particular that the unreliability applies to testing for NaN,
which with a conforming implementation would be easy, like
x != x // If so, then with conforming impl. we have a NaN.
With C++03 you could test for NaN in platform-specific ways, like using
Posix isnan macro or Visual C++ _isnan runtime library function. But it
was difficult to write portable code that way. The platform checking was
akin to browser-detection on the web: an ungood way to do things.
Happily the C++11 standard, by incorporating most of the C99 standard
library, requires a common isnan() function:
<code>
#include <iostream>
#include <math.h> // is_nan
#include <limits> // std::numeric_limits
#ifdef _MSC_VER
inline int isnan( double x ) { return _isnan( x ); }
#endif
int main()
{
using namespace std;
typedef numeric_limits<double> Fp;
cout << boolalpha;
cout << "Example NaN output: " << Fp::quiet_NaN() << endl;
cout << "3.15 is NaN? " << !!isnan( 3.14 ) << endl;
cout << "NaN is NaN? " << !!isnan( Fp::quiet_NaN() ) << endl;
}
</code>
The above code reflects that std::isnan() is not yet implemented in
Visual C++ 10.0, which is the current version of Visual C++.
Cheers & hth.,
- Alf