Compare two doubles to see if they are the same NaN

206 Views Asked by At

I have two doubles x and y with y known to be a particular NaN value, I'd like to see if they are bitwise identical. That is, I want to determine if x is exactly the same NaN value as y.

NaNs cannot be usefully compared with the == opeator since NaNs are never equal to any other value (not even themselves!).

Is there something better than the following "bitwise equal" approach (and is this approach legal?):

bool bitwise_equal(double x, double y) {
    unsigned char xbytes[sizeof(x)];
    unsigned char ybytes[sizeof(y)];
    memcpy(xbytes, &x, sizeof(x));
    memcpy(ybytes, &y, sizeof(y));
    return memcmp(xbytes, ybytes, sizeof(x)) == 0;
}
1

There are 1 best solutions below

1
On

Compare two doubles to see if they are the same NaN

if they are bitwise identical

I want to determine if x is exactly the same NaN value as y.

Directly comparing bits patterns with memcmp() is a reasonable approach.

C does not specify much detail about NaN payload sameness. Note: An implementation may defined "same" with multiple bit-patterns. See sign consideration.

#include <math.h>
#include <stdbool.h>
#include <string.h>

bool NaN_bitwise_equal(double x, double y) {
    return isnan(x) && isnan(y) && memcmp(&x, &y, sizeof x) == 0;
}

"same NaN value" is something of a contradiction as the values are not numerically value comparable, but the NaN payload may be.