thinkIn
V2EX  ›  C

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

  •  
  •   thinkIn · Nov 12, 2015 · 2557 views
    This topic created in 4009 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
    thinkIn
    OP
    Nov 12, 2015
    1
    看来还是要 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
    nashge
    Nov 12, 2015
    2
    知道浮点数在计算机中的表示,就能理解上面一段代码了
    thinkIn
    thinkIn
    OP
    Nov 12, 2015 via iPhone
    3
    @nashge 嗯,是的呢。主要就是想弄清楚第二种方法。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1318 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 20:05 · PVG 04:05 · LAX 12:05 · JFK 15:05
    ♥ Do have faith in what you're doing.