Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't the floating point types compare by using memcmp() function?

Tags:

c

bool floatcmp(const float a, const float b)
{
    const void *p = (void*)&a;
    const void *q = (void*)&b;
    if (memcmp(p, q, sizeof(float)) == 0)
        return true;
    return false;
}

The example code is above, the man page says memcmp(x,y)==0 does not imply that x==y and floating point types often have a value called NaN (‘not a number’) with the property that NaN==NaN is false. But I change the type to void* and I think the compiler doesn't know a is a float number.

like image 536
myanl Avatar asked Apr 25 '26 18:04

myanl


1 Answers

For IEEE 754 binary floating point there are two important cases where a bit by bit equality comparison will produce different results from a floating point equality comparison.

The first and probably most important is zero. IEEE 754 has representations for both positive zero and negative zero. These will compare equal in a floating point comparison but unequal in a bitwise comparison.

The second is NaNs, comparisions involving NaNs, even equality to another identical NaN are always false, but under bitwise comparison two identical NaNs will compare the same.

like image 77
plugwash Avatar answered Apr 27 '26 09:04

plugwash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!