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

2015-11-12 16:11:46 +08:00
 thinkIn
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; 有什么原理吗?查了半天没找到,这是怎么回事呢?

1211 次点击
所在节点    C
3 条回复
thinkIn
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
2015-11-12 18:45:36 +08:00
知道浮点数在计算机中的表示,就能理解上面一段代码了
thinkIn
2015-11-12 19:07:54 +08:00
@nashge 嗯,是的呢。主要就是想弄清楚第二种方法。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/235675

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX