If operator< works properly for floating-point types, why can't we use it for equality testing?

前端 未结 5 1374
借酒劲吻你
借酒劲吻你 2021-01-01 16:55

Properly testing two floating-point numbers for equality is something that a lot of people, including me, don\'t fully understand. Today, however, I thought about how some s

5条回答
  •  悲哀的现实
    2021-01-01 17:08

    The following code (which I changed so it compiles: Specifically the call to floateq was changed to floatcmp) prints out float->double vs double: 1 0 , not 0 0 (as one would expect when comparing those two values as floats).

    #include 
    
    bool floatcmp(float a, float b) {
        //check NaN
        return !(a < b) && !(b < a);
    }
    
    int main()
    {
        std::cout << "float->double vs double: "
                  << floatcmp(static_cast(0.7f), 0.7) << " "
                  << (static_cast(0.7f) == 0.7) << "\n";
    }
    

    However what matters for the standard library is that operator< defines a strict weak ordering, which it in fact does for floating point types.

    The problem with equality is that two values may look the same when rounded to say 4 or 6 places but are in fact totally different and compare as not equal.

提交回复
热议问题