Comparing floating point number to zero

后端 未结 9 967
时光说笑
时光说笑 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:20

    Simple comparison of FP numbers has it's own specific and it's key is the understanding of FP format (see https://en.wikipedia.org/wiki/IEEE_floating_point)

    When FP numbers calculated in a different ways, one through sin(), other though exp(), strict equality won't be working, even though mathematically numbers could be equal. The same way won't be working equality with the constant. Actually, in many situations FP numbers must not be compared using strict equality (==)

    In such cases should be used DBL_EPSIPON constant, which is minimal value do not change representation of 1.0 being added to the number more than 1.0. For floating point numbers that more than 2.0 DBL_EPSIPON does not exists at all. Meanwhile, DBL_EPSILON has exponent -16, which means that all numbers, let's say, with exponent -34, would be absolutely equal in compare to DBL_EPSILON.

    Also, see example, why 10.0 == 10.0000000000000001

    Comparing dwo floating point numbers depend on these number nature, we should calculate DBL_EPSILON for them that would be meaningful for the comparison. Simply, we should multiply DBL_EPSILON to one of these numbers. Which of them? Maximum of course

    bool close_enough(double a, double b){
        if (fabs(a - b) <= DBL_EPSILON * std::fmax(fabs(a), fabs(b)))
        {
            return true;
        }
        return false;
    }
    

    All other ways would give you bugs with inequality which could be very hard to catch

提交回复
热议问题