I came across this code that spews a warning with gcc
:
float f;
// Calculate a value for f
if (!f == 0.0)
{
// Handle it being non-zero
}
It was probably just a typo by another team member, and examining the code what was really meant was:
if (f != 0.0)
// OR
if (!(f == 0.0))
I've corrected the code, but I was just wondering what would !NaN
evaluate to. We use the f
value inside the if
, so we don't want NaN
s getting past the check.
The convenience of an isNaN function Unlike all other possible values in JavaScript, it is not possible to use the equality operators (== and ===) to compare a value against NaN to determine whether the value is NaN or not, because both NaN == NaN and NaN === NaN evaluate to false .
The math. isnan() method checks whether a value is NaN (Not a Number), or not. This method returns True if the specified value is a NaN, otherwise it returns False.
NaN (Not a Number) is a numeric data type that means an undefined value or value that cannot be represented, especially results of floating-point calculations.
Definition and Usage. In JavaScript NaN is short for "Not-a-Number". The isNaN() method returns true if a value is NaN. The isNaN() method converts the value to a number before testing it.
If you want to avoid a NaN inside if
, you can use the function
bool isnan( float arg );
to perform a check.
From the reference of the function:
NaN values never compare equal to themselves or to other NaN values. Copying a NaN is not required, by IEEE-754, to preserve its bit representation (sign and payload), though most implementation do.
Another way to test if a floating-point value is NaN is to compare it with itself:
bool is_nan(double x) { return x != x; }
The C++ draft (N4713) states:
8.5.2.1 Unary operators [expr.unary.op]
...
9. The operand of the logical negation operator!
is contextually converted to bool (Clause 7); its value istrue
if the converted operand isfalse
andfalse
otherwise. The type of the result is bool.7.14 Boolean conversions [conv.bool]
1. A prvalue of arithmetic, unscoped enumeration, pointer, or pointer-to-member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true.
Conclusion: As NaN is contextually converted as true
in the expression !NaN
, !NaN
is false
and thus not a NaN.
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