floating point comparison

NOTE: The following content is taken from Hu Fan and Zeng Lei's "Algorithm Notes".
After a lot of calculations, 3.14 may be stored as 3.1400000000001, or 3.1499999999999, so the two numbers are not equal. Therefore, it is necessary to introduce a very small number eps to correct the error. Experience shows that 10^-8 is more suitable.

1. == operator

So if a number a is between [b-eps, b+eps], it is considered that a==b is established

#include<stdio.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("true\n");
    }
    else{
        printf("false\n");
    }
    return 0;
}

2. Greater than operator (>)

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

3. Less than operator (<)

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

4. Greater than or equal operator (<=)

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

5. Less than or equal operator (<=)

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

6, pi

const double Pi =acos(-1.0);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325610091&siteId=291194637