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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With