Should we compare floating point numbers for equality against a *relative* error?

前端 未结 5 1434
闹比i
闹比i 2020-11-30 09:13

So far I\'ve seen many posts dealing with equality of floating point numbers. The standard answer to a question like \"how should we decide if x and y are equal?\" is

<
5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 09:41

    Using relative error is at least not as bad as using absolute errors, but it has subtle problems for values near zero due to rounding issues. A far from perfect, but somewhat robust algorithm combines absolute and relative error approaches:

    boolean approxEqual(float a, float b, float absEps, float relEps) {
        // Absolute error check needed when comparing numbers near zero.
        float diff = abs(a - b);
        if (diff <= absEps) {
            return true;
        }
    
        // Symmetric relative error check without division.
        return (diff <= relEps * max(abs(a), abs(b)));
    }
    

    I adapted this code from Bruce Dawson's excellent article Comparing Floating Point Numbers, 2012 Edition, a required read for anyone doing floating-point comparisons -- an amazingly complex topic with many pitfalls.

提交回复
热议问题