How to compare two NAN values in C++ - c++

I have an application in which a code area produces NAN values. I have to compare the values for equality and based on that execute the rest of the code.How to compare two NAN values in C++ for equality?

Assuming an IEEE 754 floating point representation, you cannot compare two NaN values for equality. NaN is not equal to any value, including itself. You can however test if they are both NaN with std::isnan from the <cmath> header:
if (std::isnan(x) && std::isnan(y)) {
// ...
}
This is only available in C++11, however. Prior to C++11, the Boost Math Toolkit provides some floating point classifiers. Alternatively, you can check if a value is NaN by comparing it with itself:
if (x != x && y != y) {
// ...
}
Since NaN is the only value that is not equal to itself. In the past, certain compilers screwed this up, but I'm not sure of the status at the moment (it appears to work correctly with GCC).
MSVC provides a _isnan function.
The final alternative is to assume you know the representation is IEEE 754 and do some bit checking. Obviously this is not the most portable option.

Regarding pre-C++11, there's a boost for that, too.
#include <boost/math/special_functions/fpclassify.hpp>
template <class T>
bool isnan(T t); // NaN.

Any given NaN is not equal to anything, it will never be equal to any other NaN, so comparing them against each other is a futile exercise.
From GNU docs:
NaN is unordered: it is not equal to, greater than, or less than anything, including itself. x == x is false if the value of x is NaN. source

Related

What is result of comparison of double and NaN?

I have the following program:
#include <iostream>
#include <cmath>
int main() {
double a = 1;
double b = nan("");
std::cout << (a > b) << std::endl;
std::cout << (b > a) << std::endl;
return 0;
}
Output:
0
0
In general from the meaning of nan - not a number it is clear that any operation with nan is essentially pointless. From IEEE-754 that I found in internet I found what if in FPU at least one of operands is nan the result is also nan, but I found nothing about comparison between normal value and nan as in example above.
What does standard say about it?
What does standard say about it?
The C++ standard does not say how operations on NaNs behave. It is left unspecified. So, as far as C++ is concerned, any result is possible and allowed.
ANSI/IEEE Std 754–1985 says:
5.7. Comparison
... Every NaN shall compare unordered with everything, including itself. ...
What unordered means exactly is shown in the Table 4 in the same section. But in short, this means that the comparison shall return false, if any of the operands is NaN, except != shall return true.
The 0 you're seeing means false in this case as that's what the stream shows for false by default. If you want to see it as true or false use std::boolalpha:
std::cout << std::boolalpha << (a > b) << std::endl;
Whey comparing floating point values where one of the values is nan then x<y, x>y, x<=y, x>=y, and x==y will all evaluate to false, whereas x!=y will always be true. Andrew Koenig has a good article on this on the Dr Dobbs website.
When you think about it the result cannot be nan since comparison operators need to return a boolean which can only have 2 states.
0 here means false.
Nan is not equal or comparable to any value so the result of operation is false(0).
Well, on top of #user2079303 pretty good answer, there are two NaNs: quiet NaN and signaling NaN. You could check std::numeric_limits<T>::has_signaling_NaN on your platform is signaling NaN is available. If it is true and value contains std::numeric_limits<T>::signaling_NaN, then
When a signaling NaN is used as an argument to an arithmetic expression, the appropriate floating-point exception may be raised and the NaN is "quieted", that is, the expression returns a quiet NaN.
To really get FP exception you might want to set FPU control word (for x87 unit) or MXCSR register (for SSE2+ unit). This is true for x86/x64 platform, check your platform docs for similar functionality

What kind of C++ constant/macro is -1.#IND?

The Math "pow" function returns -1.#IND. What kind of error value is -1.#IND and how do I detect the error in an if-statement?
-1.#IND is the textual representation of NaN on Windows.
You can check if a float value is NaN with this small function:
// NaN never compares equal, not even to itself
bool is_nan(double d){ return d != d; }
(As #chris notes, if you have a C++11 compliant stdlib, you get std::isnan in <cmath>.)
In normal program flow, you shouldn't need to worry about NaN as long as you sanity-check your math inputs. Of course, you can also go the other way and just do your math calculations and check against NaN afterwards. :)
The value you see is a representation for NaN or not a number. These values show up as a result of a floating point operation which has an undefined value. For example, 0.0 / 0.0 will yield a NaN. There are a number of other situations where a NaN is produced. If you want to determine if a floating point value is a NaN, you can test for them:
if (std::isnan(value)) {
...
}
There are few other other special values which can be produced as the result of floating point operations, e.g., positive or negative infinity and there are tests in <cmath> for these, as well.
-1#IND normally happens when you have a /0 somewhere in your code. Protect against it by checking all denominators or bases in pow functions with -ve exponents for 0's.
Once the division or pow operation has been completed, if you didn't check your inputs, check your outputs with:
if (output != output) return 0; // or some default
else return output;
-1.#IND is a NaN, not a number. NaNs arise for many reasons. Expressions such as 0.0/0.0 are indeterminate; you'll get a NaN if you try. The square root of -1 (or of any negative real) is pure imaginary; use the float or double sqrt function and you'll get a NaN as a result. Here the result is not indeterminate, but it is not real, either. It's a NaN.
Another way to express sqrt(-1.0) is pow(-1.0, 0.5). This also generates a NaN.

Checking if a complex number has NaN

I'm trying to check if a std::complex number that is a result of a fourier transform (using http://fftw.org/) contains a NaN in either the real or imag part.
I'm using Borland C++, so I don't have access to std::isnan. I have tried to check if the number is NaN by comparing it to itself:
(n.imag() != n.imag())
However, as soon as I call the n.imag() or std::imag(n), I get a "floating point invalid operation".
Is there any way to validate if a std::complex is good; if it contains a NaN?
This works on g++ :
#include<iostream>
#include<cmath>
#include<complex>
int main(){
double x=sqrt(-1.);
std::complex<double> c(sqrt(-1.), 2.);
std::cout<<x<<"\n";
std::cout<<c<<"\n";
std::cout<< ( (c!=c) ? "yup" : "nope" )<<"\n";
}
From the float.h header
int _isnan(double d);
Returns a nonzero value (TRUE) if the value passed in is a NaN; otherwise it returns 0 (FALSE).
int _fpclass(double __d);
Returns an integer value that indicates the floating-point class of its argument. The possible values are defined in FLOAT.H (NaN, INF, etc.)
Is there fpclassify() in math.h? It should return FP_NAN for NaNs. Or better yet use isnan(). If there are no such functions/macros, you may look at the binary representation of your floats or doubles and check manually for NaNs. See IEEE-754 single and double precision formats for details.
I found out that Borland has its own math library. So if you want to avoid floating point errors, use IsNan from Borlands Math.
http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/Math_IsNan#Double.html

Is there a double value which will remain itself despite any computation applied to it?

On the Windows XP..7 platforms, for x86 instruction sets, using standard C++ or a Microsoft compiler, is there a value I can assign a double which, when other computations are applied to it, will always result in that same value?
e.g.
const double kMagicValue = ???;
double x = kMagicValue;
cout << x * 9.1; // still outputs kMagicValue
As I understand it, there is a floating point error condition that once trigged, the remainder of all floating point computations will result in NAN or something similar...
I ask because I have a series of functions that try to compute a double for a given input, and for some inputs, "no answer (NAN)" is a good output (conceptually).
And I want to be able to be lazy, and string together computations that should, if any part results in NAN, result as a whole in NAN (i.e. kMagicValue).
Quiet NaN should do just fine. You can get it from std::numeric_limits<double>::quiet_NaN() by including the <limits> header. There's also a signaling NaN, but using it will usually result in an exception.
Remember however, that you can't simple use mydouble == qNaN, since NaN compares equal to nothing, not even itself. You have to use that property of NaN to test it: bool isNaN = mydouble != mydouble;.
Any floating point operation involving NaN results in NaN again (to my knowledge). Moreover, NaN compares unequal to itself, and it is unique among IEEE754 floats with this property. So, to test for it:
bool is_nan(double x) { return x != x; }
If you have C++11 support, you can use std::isnan(x) != 0 or std::fpclassify(x) == std::FP_NAN from <cmath> instead [thanks #James Brock].
To make it:
double make_nan() {
assert(std::numeric_limits<double>::has_quiet_NaN);
return std::numeric_limits<double>::quiet_NaN();
}
You shouldn't rely on NaN to do the job. It will always compare false to any value, including itself, and you have to make sure that the platform respects IEEE754 semantics to a certain extent (this includes having a NaN in the first place).
See horror stories there: Negative NaN is not a NaN?
If you really want this approach, and you are confident enough about IEEE754 support, be sure to compile with /fp:precise (since you use MSVC) so that the compiler doesn't optimize away stuff like 0 * NaN. Be aware that this might impact performance.
To get a NaN,
std::numeric_limits<double>::quiet_NaN()
To test for NaN
inline bool is_NaN(double x) { return !(x == x); }
But this approach is probably more trouble than it is worth. I'd rather use exceptions for control flow here.
The right thing to use is boost::optional<double>, but it can be a little verbose at some places
[Also, the Haskell language has first-class support for these kind of control flow, if C++ is not a must-go option, Maybe you can give it a try.]
Actually there is a special floating point value named Not-A-Number (NaN). Any expression with NaN involved will return NaN.
#include <limits>
numeric_limits<double>::quiet_NaN()
Infinity not always remains the same. For example it become NaN if you try to divide on Infinity.

How do you check for infinite and indeterminate values in C++?

In my programs infinity usually arises when a value is divided by zero. I get indeterminate when I divide zero by zero. How do you check for infinite and indeterminate values in C++?
In C++, infinity is represented by 1.#INF. Indeterminate is represented by -1.#IND. The problem is how to test if a variable is infinite or indeterminate. Checking infinity is relatively straightforward: You find the infinity definition in your particular C++. For my case (VS2003), it is std::numeric_limits::infinity(). You have to include "limits" in order to use it. You can assign this infinite value to a variable and you can compare it to some value in order to check if that value is infinite.
Indeterminate is a little tricky, because you cannot compare an indeterminate value to some other value. Any comparison returns false. You can use this property to detect an indeterminate value by comparing it to itself. Let's say you have a double variable called aVal. Under normal conditions, aVal != aVal returns false. But if the value is indeterminate, aIndVal != aIndVal returns true. This weird situation is not present for infinite values, i.e. aInfVal != aInfVal always returns false.
Here are two functions that can be used to check for indeterminate and infinite values:
#include "limits.h"
#include "math.h"
bool isIndeterminate(const double pV)
{
return (pV != pV);
}
bool isInfinite(const double pV)
{
return (fabs(pV) == std::numeric_limits::infinity())
}
Are there better ways for these checks, am I missing anything?
For Visual Studio I would use _isnan and _finite, or perhaps _fpclass.
But if you have access to a C++11-able standard library and compiler you could use std::isnan and std::isinf.
Although C++03 doesn't provide C99's isnan and isinf macros, C++11 standardizes them by providing them as functions. If you can use C++11, instead of strict C++03, then these would be cleaner options, by avoiding macros, compiler built-ins and platform-dependant functions.
C++11's std::isfinite returns true for all values except inf and nan; so !isfinite should check for infinite and indeterminate values in one shot.
Although not strictly a part of C++03, if your compiler provides some of the new C99 features of the standard <math.h> header file, then you may have access to the following "function-like macros": isfinite, isinf, isnan. If so, these would be the easiest and safest way to perform these checks.
You may also use these as a strict C++-only solution. They don't really offer more than the OP's solution except added security through use of type traits and perhaps the tiniest speed boost in the case of is_inf.
template <bool> struct static_assert;
template <> struct static_assert<true> { };
template<typename T>
inline bool is_NaN(T const& x) {
static_cast<void>(sizeof(static_assert<std::numeric_limits<T>::has_quiet_NaN>));
return std::numeric_limits<T>::has_quiet_NaN and (x != x);
}
template <typename T>
inline bool is_inf(T const& x) {
static_cast<void>(sizeof(static_assert<std::numeric_limits<T>::has_infinity>));
return x == std::numeric_limits<T>::infinity() or x == -std::numeric_limits<T>::infinity();
}
(beware of self-made static_assert)
There's isfinite from C99 or POSIX or something I think.
One hackish way to do it is to test x-x == 0; if x is infinite or NaN, then x-x is NaN so the comparison fails, while if x is finite, then x-x is 0 and the comparison succeeds. I'd recommend using isfinite, though, or packaging this test into a function/macro called something like isfinite so you can get rid of it all when the time comes.
if (x!=x) ... then x is nan
if (x>0 && x/x != x/x) ... then x is +inf
if (x<0 && x/x != x/x) ... then x is -inf
this might also work (but involves call to exp() and testing equality of doubles):
if (exp(-x)==0.) ... then x is inf
if (exp(x)==0.) ... then x is -inf