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?
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 .
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.
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.
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.
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.
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 andfalse
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
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