Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is !NaN not a NaN?

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 NaNs getting past the check.

like image 300
Ken Y-N Avatar asked Oct 22 '18 06:10

Ken Y-N


People also ask

Why is NaN == NaN false?

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 .

Is not NaN in Python?

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.

Does NaN stand for not a number?

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.

Is not a NaN?

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.


1 Answers

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 is true if the converted operand is false and false 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.

like image 61
P.W Avatar answered Oct 25 '22 21:10

P.W