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

前端 未结 5 1376
借酒劲吻你
借酒劲吻你 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:28

    Generally all comparison operations on floating point numbers should be done within a specified precision limit. Otherwise, you may be bitten by accumulated rounding error which is not seen at low precision, but will be taken into account by comparison operators. It just often doesn't matter much for sorting.

    Another code sample which does show that your comparison doesn't work (http://ideone.com/mI4S76).

    #include 
    
    bool floatcmp(float a, float b) {
        //check NaN
        return !(a < b) && !(b < a);
    }
    
    int main() {
        using namespace std;
    
        float a = 0.1;
        float b = 0.1;
    
        // Introducing rounding error:
        b += 1;
        // Just to be sure change is not inlined
        cout << "B after increase = " << b << endl;
        b -= 1;
        cout << "B after decrease = " << b << endl;
    
        cout << "A " << (floatcmp(a, b) ? "equals" : "is not equal to") << "B" << endl;
    }
    

    Output:

    B after increase = 1.1
    B after decrease = 0.1
    A is not equal toB
    

提交回复
热议问题