c++ comparing two floating point values

前端 未结 5 1292
陌清茗
陌清茗 2020-12-30 15:58

I\'m wondering what is the difference for comparing two double between this two manner :

double a1 = ...;
double a2 = ....;
  1. fabs(a1-a
5条回答
  •  独厮守ぢ
    2020-12-30 16:08

    This has already been pretty well addressed, but a few points are in order:

    fabs(a1-a2) < epsilon
    

    is comparing the absolute difference between a1 and a2 to the tolerance epsilon. This may be appropriate if you know the scaling a priori (for example, if a2 is actually a constant), but should generally be avoided if you don't know how big a1 and a2 are.

    Your second option almost computes the relative difference, but has a bug; it should actually read:

    fabs((a1-a2)/a2) < epsilon
    

    (note that the division is inside the absolute value; otherwise, this condition is useless for negative a2). Relative error is more correct for most uses, because it more closely mirrors the way floating-point rounding actually happens, but there are situations in which it does not work and you need to use an absolute tolerance (usually this is because of catastrophic cancellation). You also will sometimes see relative error bounds written in this form:

    fabs(a1-a2) < fabs(a2)*epsilon
    

    which is often somewhat more efficient because it avoids a division.

提交回复
热议问题