Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the result of comparing a number with NaN?

Consider for example

bool fun (double a, double b) {
    return a < b;
}

What will fun return if any of the arguments are NaN? Is this undefined / implementation defined behavior?

What happens with the other relational operators and the equality operators?

like image 785
Baum mit Augen Avatar asked Jul 04 '15 21:07

Baum mit Augen


People also ask

How do you compare NaN numbers?

NaN (not-a-number) is unordered, so the numerical comparison operators < , <= , > , and >= return false if either or both operands are NaN . The equality operator == returns false if either operand is NaN , and the inequality operator != returns true if either operand is NaN .

What results in NaN?

NaN, an acronym for Not a Number is an exception that usually occurs in the cases when an expression results in a number that is undefined or can't be represented. It is used for floating-point operations. For example: The square root of negative numbers.

How NaN values behave while comparing with itself?

Why do comparisons of NaN values behave differently from all other values? That is, all comparisons with the operators ==, <=, >=, <, > where one or both values is NaN returns false, contrary to the behaviour of all other values.

What are NaN values?

In computing, NaN (/næn/), standing for Not a Number, is a member of a numeric data type that can be interpreted as a value that is undefined or unrepresentable, especially in floating-point arithmetic.


2 Answers

Any comparison(except with "!=") with NaN returns false.

Here is a table I constructed:

     +Dbl_Nan  0_Nan  Inf_Nan  NaN_NaN  +Dbl_Inf  +Dbl_-Inf  Inf_-Inf  Inf_Inf
   -----------------------------------------------------------------------
>  |  False    False  False    False     False     True      True      False
<  |  False    False  False    False     True      False     False     False
== |  False    False  False    False     False     False     False     True
!= |  True     True   True     True      True      True      True      False

Click here for the Rationale on why NaN is always false.

like image 187
SunsetQuest Avatar answered Sep 18 '22 21:09

SunsetQuest


The C++ standard merely says:

[expr.rel]/5 If both operands (after conversions) are of arithmetic or enumeration type, each of the operators shall yield true if the specified relationship is true and false if it is false.

So basically, a < b is true if a is less than b.

However, the implementation may claim conformance to IEC 559 aka IEEE 754 standard for floating point arithmetic, via numeric_limits::is_iec559. Then it is governed by that standard in section 5.7 and table 4, which requires that all comparisons but != involving NaN report false. != involving NaN reports true

like image 22
Igor Tandetnik Avatar answered Sep 17 '22 21:09

Igor Tandetnik