zoukankan      html  css  js  c++  java
  • 浮动数与0比较

    无限大小

      C语言如何表示无限大小,NANredis里面这么搞的:

    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 "

               "R_PosInf: %lf "

               "R_NegInf: %lf "

               "R_Nan   : %lf ",

               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 "

               "R_PosInf: %lf "

               "R_NegInf: %lf "

               "R_Nan   : %lf ",

               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 ", a, b);

        }else{

                printf("%lf - %lf == 0 ", 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/

  • 相关阅读:
    SplitViewController的简单使用
    ViewController容器
    AnchorPoint 和Position 关系
    __OSX_AVAILABLE_BUT_DEPRECATED
    __OSX_AVAILABLE_STARTING
    UIButton重复点击,重复触发,怎么办
    iOS小技巧:用runtime 解决UIButton 重复点击问题
    FOUNDATION_EXPORT 或#define 或 extern
    nginx第一天
    053-001
  • 原文地址:https://www.cnblogs.com/imlgc/p/3816233.html
Copyright © 2011-2022 走看看