Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is result of comparison of double and NaN?

Tags:

c++

c++11

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?

like image 825
Alex Avatar asked Apr 26 '16 09:04

Alex


3 Answers

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.

like image 69
eerorika Avatar answered Sep 21 '22 23:09

eerorika


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.

like image 21
Sean Avatar answered Sep 17 '22 23:09

Sean


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

like image 31
Alikbar Avatar answered Sep 21 '22 23:09

Alikbar