What is the result of comparing doubles 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 the general case, it is clear from the meaning of nan - not a number that any operation with nan is essentially meaningless. From IEEE-754 , which I found on the Internet, I found that if at least one of the operands nan in the FPU, the result is also nan , but I did not find anything about the comparison between the normal value and nan , as in the example above.

What does the standard say about this?

+5
source share
4 answers

What does the standard say about this?

The C ++ standard does not talk about how operations on NaN behave. It is left unspecified. So, as for C ++, any result is possible and resolved.

ANSI / IEEE Std 754-1985 says:

5.7. Comparison

... Each NaN will compare unordered with everything, including itself ....

What unordered means exactly is shown in Table 4 in the same section. But, in short, this means that the comparison returns false if any of the operands is NaN, except that != Returns true.

+7
source

The 0 you display means false in this case, like 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; 

The serum compares the floating point values, where one of the values โ€‹โ€‹is nan, then x<y , x>y , x<=y , x>=y and x==y will be evaluated as false, while x!=y will always be true, Andrew Koenig has a good article about this on the Dr Dobbs website.

When you think about this, the result cannot be nan , since comparison operators must return a boolean value that can contain only 2 states.

+2
source

0 here means false. Nan is not equal to or comparable to any value, so the result of the operation is false (0).

+1
source

Well, at the top of @ user2079303, the answer is pretty good, there are two NaNs: quiet NaN and NaN alarm. You can check std::numeric_limits<T>::has_signaling_NaN on your platform, signaling that NaN is available. If it is true, and the value contains std::numeric_limits<T>::signaling_NaN , then

When the NaN signaling is used as an argument for an arithmetic expression, the corresponding floating-point exception can be raised and the NaN is soothing, that is, the expression returns a quiet NaN.

To actually get an FP exception, you may need to set the FPU control word (for x87) or the MXCSR register (for SSE2 +). This is true for the x86 / x64 platform, check your platform docs for similar functionality

0
source

Source: https://habr.com/ru/post/1247924/


All Articles