无限大小
C语言如何表示无限大小,NAN?redis里面这么搞的:
static double R_Zero, R_PosInf, R_NegInf, R_Nan;
/* Double constants initialization */
R_Zero = 0.0;
R_PosInf = 1.0/R_Zero;
R_NegInf = -1.0/R_Zero;
R_Nan = R_Zero/R_Zero;
简单测试:
#include <stdio.h>
int main()
{
static double R_Zero, R_PosInf, R_NegInf, R_Nan;
/* Double constants initialization */
R_Zero = 0.0;
R_PosInf = 1.0/R_Zero;
R_NegInf = -1.0/R_Zero;
R_Nan = R_Zero/R_Zero;
printf("R_Zero : %lf\n"
"R_PosInf: %lf\n"
"R_NegInf: %lf\n"
"R_Nan : %lf\n",
R_Zero, R_PosInf, R_NegInf, R_Nan);
return 0;
}
结果如下:
[heidong@HEIDONGVM tmp]$ ./z
R_Zero : 0.000000
R_PosInf: inf
R_NegInf: -inf
R_Nan : -nan
果然神奇。
浮动数与0比较
大学时候,老师教导我们,浮动数不要与0比较,因为浮点数在计算机里面表示的是近似值。所以如果浮动数要与0做比较就用·< 0.000001·这种龌蹉的方式,明明是0,却要搞个神马0.000001出来。现在我们可以这么来稿了:
#include <stdio.h>
int main()
{
static double R_Zero, R_PosInf, R_NegInf, R_Nan;
/* Double constants initialization */
R_Zero = 0.0;
R_PosInf = 1.0/R_Zero;
R_NegInf = -1.0/R_Zero;
R_Nan = R_Zero/R_Zero;
printf("R_Zero : %lf\n"
"R_PosInf: %lf\n"
"R_NegInf: %lf\n"
"R_Nan : %lf\n",
R_Zero, R_PosInf, R_NegInf, R_Nan);
double a = 1.0;
double b = 1.0;
if(a-b == R_NegInf) {
printf("%lf - %lf != 0\n", a, b);
}else{
printf("%lf - %lf == 0\n", a, b);
}
return 0;
}
结果如下:
[heidong@HEIDONGVM tmp]$ ./z
R_Zero : 0.000000
R_PosInf: inf
R_NegInf: -inf
R_Nan : -nan
1.000000 - 1.000000 == 0
以后就可以用R_NegInf这种方式和0比较了。
POST A:T http://luoguochun.cn/2014/06/28/infinite/
原文地址:http://www.cnblogs.com/imlgc/p/3816233.html