浮点数在计算机中的存储是并不总是精准的,在经过容易造成误差的计算之后,会产生偏差,因此需要引入一个极小数eps来对这种误差进行修正
eps取比较合适
#include<stdio.h>
#include<math.h>
const double eps = 1e-8;
#define Equ(a,b) ((fabs((a) - (b)))<(eps))
int main(){
double db1 = 4 * asin(sqrt(2) / 2);
double db2 = 3 * asin(sqrt(3) / 2);
if(db1 == db2){
printf("true!\n");
}else printf("false!\n");
return 0;
}
很显然,两者不相等,因为精度损失太多了!
#include<stdio.h>
#include<math.h>
const double eps = 1e-8;
#define Equ(a,b) ((fabs((a) - (b)))<(eps))
int main(){
double db1 = 4 * asin(sqrt(2) / 2);
double db2 = 3 * asin(sqrt(3) / 2);
if (Equ(db1,db2))
{
/* code */
printf("true!\n");
}else printf("false!\n");
return 0;
}
这样才是正确的!
const double eps = 1e-8;
const double pi = acos(-1);
#define Equ(a,b) ((fabs((a) - (b)))<(eps))
#define More(a,b) (((a) - (b)) > (eps))
#define Less(a,b) (((a) - (b)) < (-eps))
#define MoreEqu(a,b) (((a) - (b)) > (-eps))
#define LessEqu(a,b) (((a) - (b)) < (eps))