###无限大小 C语言如何表示无限大小,NAN?redis里面这么搞的:

1
2
3
4
5
6
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;    

简单测试:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#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;
}

结果如下:

1
2
3
4
5
[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出来。现在我们可以这么来稿了:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#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;
}

结果如下:

1
2
3
4
5
6
[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比较了。