V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
thinkIn
V2EX  ›  C

看到一个判断 NAN( not a number)的方法,不知原理,请大家帮帮忙解释下?

  •  
  •   thinkIn · 2015-11-12 16:11:46 +08:00 · 1394 次点击
    这是一个创建于 3326 天前的主题,其中的信息可能已经有所发展或是发生改变。
    union float_ieee{
        int i;
        float f;
    };
    
    int is_nanf(float x){
    #if 0
        int t;
        union float_ieee e;
    
        e.f=x;
        t=e.i&0x7fffffff;
        t=0x7f800000-t;
        return ((unsigned)t>>31);
    #endif
        return x!=x;  
    }
    

    其中第二种方法 return x!=x; 有什么原理吗?查了半天没找到,这是怎么回事呢?

    3 条回复    2015-11-12 19:07:54 +08:00
    thinkIn
        1
    thinkIn  
    OP
       2015-11-12 16:26:01 +08:00
    看来还是要 google 啊。

    In comparison operations, positive infinity is larger than all values except itself and NaN, and negative infinity is smaller than all values except itself and NaN. NaN is unordered: it is not equal to, greater than, or less than anything, including itself. x == x is false if the value of x is NaN. You can use this to test whether a value is NaN or not, but the recommended way to test for NaN is with the isnan function (see Floating Point Classes). In addition, <, >, <=, and >= will raise an exception when applied to NaNs.

    -----https://www.gnu.org/software/libc/manual/html_node/Infinity-and-NaN.html#Infinity-and-NaN
    nashge
        2
    nashge  
       2015-11-12 18:45:36 +08:00
    知道浮点数在计算机中的表示,就能理解上面一段代码了
    thinkIn
        3
    thinkIn  
    OP
       2015-11-12 19:07:54 +08:00 via iPhone
    @nashge 嗯,是的呢。主要就是想弄清楚第二种方法。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2683 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 12:46 · PVG 20:46 · LAX 04:46 · JFK 07:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.