C ++ notes (5) - Comparison of floating point numbers

Determine whether the same

Because a floating-point storage is not always accurate, for example through a lot after the calculation might 3.14be saved as 3.1400000000001or 3.1439999999999, at this time if the direct use ==to compare the two numbers, then outputs erroneous results, false(C ++ in ==only two it is determined that a case where identical numbers is true). It is necessary to introduce a minimum number of epscorrected, without departing the error, then it is determined true.

Usually defined a epsis a constant 1e-8:

const double eps = 1e-8;

Corresponding to the definition of the operation determines whether or equal to Equ:

#define Equ(a, b) ((fabs((a)-(b))<(eps))

Above this line is defined by a named macro definition Equfunction, this function will subtract a and b, if the absolute value of the difference is smaller than the minimum result of eps, then the determination is true, otherwise false. The above plus so many parentheses to prevent errors may bring macro definition, can not be omitted. Correspondingly, if the need is not equal, you only need !Equ(a, b)to.

Examples of the above-mentioned functions:

#include <stdio.h>
#include <math.h>

const double eps = 1e-8;
#define Equ(a,b) ((fabs((a) - (b)) < (eps))

int main(){
    double db = 1.23;
    if(Equ(db, 1.23)){
        printf("equal");
    }
    else{
        printf("not equal")
    }
    return 0;
}

more than the

#define More(a,b) (((a) - (b)) > (eps))

Less than

#define Less(a,b) (((a)-(b)) < (-eps))

greater or equal to

#define MoreEqu(a,b) (((a)-(b))>(-eps))

Less than or equal

#define LessEqu(a,b) (((a)-(b))<(eps))

Added: pi

\ (\ COS {\ = PI} -1 \) , \ (\ = PI \ arccos {-1} \) , so that:

const double Pi = acos(-1.0);

Errors associated with supplement

Moreover:

  1. After a large number of calculations may be because of the cumulative error, stored in a variable 0 is actually a very small negative number, if this time to the variable square root operation sqrt, it will complain ( asin(x)Similarly, when stored x+1 a similar situation occurs or -1). Eps therefore need to ensure that the variables in the domain of definition;
  2. Some compiler environment variables may become -0.00 0.00 at the output. This is a bug, only then will result in the string and -0.00, and if successful then compare the results to back eps plus 0.00.

reference

"Algorithm notes," Hu, who with

Guess you like

Origin www.cnblogs.com/yejianying/p/cpp_notes_5.html