V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
thinkIn
V2EX  ›  C

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

  •  
  •   thinkIn · Nov 12, 2015 · 2122 views
    This topic created in 3825 days ago, the information mentioned may be changed or developed.
    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 replies    2015-11-12 19:07:54 +08:00
    thinkIn
        1
    thinkIn  
    OP
       Nov 12, 2015
    看来还是要 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  
       Nov 12, 2015
    知道浮点数在计算机中的表示,就能理解上面一段代码了
    thinkIn
        3
    thinkIn  
    OP
       Nov 12, 2015 via iPhone
    @nashge 嗯,是的呢。主要就是想弄清楚第二种方法。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   971 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 23:41 · PVG 07:41 · LAX 16:41 · JFK 19:41
    ♥ Do have faith in what you're doing.