Comparing floating point number to zero

后端 未结 9 969
时光说笑
时光说笑 2020-11-28 23:04

The C++ FAQ lite \"[29.17] Why doesn\'t my floating-point comparison work?\" recommends this equality test:

#include   /* for std::abs(double) *         


        
9条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 23:28

    No.

    Equality is equality.

    The function you wrote will not test two doubles for equality, as its name promises. It will only test if two doubles are "close enough" to each other.

    If you really want to test two doubles for equality, use this one:

    inline bool isEqual(double x, double y)
    {
       return x == y;
    }
    

    Coding standards usually recommend against comparing two doubles for exact equality. But that is a different subject. If you actually want to compare two doubles for exact equality, x == y is the code you want.

    10.000000000000001 is not equal to 10.0, no matter what they tell you.

    An example of using exact equality is when a particular value of a double is used as a synonym of some special state, such as "pending calulation" or "no data available". This is possible only if the actual numeric values after that pending calculation are only a subset of the possible values of a double. The most typical particular case is when that value is nonnegative, and you use -1.0 as an (exact) representation of a "pending calculation" or "no data available". You could represent that with a constant:

    const double NO_DATA = -1.0;
    
    double myData = getSomeDataWhichIsAlwaysNonNegative(someParameters);
    
    if (myData != NO_DATA)
    {
        ...
    }
    

提交回复
热议问题