無限大小
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/