If I copy a float to another variable, will they be equal?

后端 未结 5 1087
猫巷女王i
猫巷女王i 2021-01-30 00:11

I know that using == to check equality of floating-point variables is not a good way. But I just want to know that with the following statements:



        
5条回答
  •  情深已故
    2021-01-30 00:19

    Yes, in all cases (disregarding NaNs and x87 issues), this will be true.

    If you do a memcmp on them you will be able test for equality while being able to compare NaNs and sNaNs. This will also require the compiler to take the address of the variable which will coerce the value into a 32-bit float instead of an 80-bit one. This will eliminate the x87 issues. The second assertion here is intended to fail to show that == will not compare NaNs as true:

    #include 
    #include 
    #include 
    
    int main(void)
    {
        float x = std::nan("");
        float y = x;
        assert(!std::memcmp(&y, &x, sizeof(float)));
        assert(y == x);
        return 0;
    }
    

    Note that if the NaNs have a different internal representation (i.e. differing mantissa), the memcmp will not compare true.

提交回复
热议问题