负NaN不是NaN? [英] Negative NaN is not a NaN?
问题描述
在编写一些测试用例时,一些测试检查了NaN的结果。
While writing some test cases, and some of the tests check for the result of a NaN.
我尝试使用 std :: isnan
但是assert失败:
I tried using std::isnan
but the assert failes:
Assertion `std::isnan(x)' failed.
打印 x
的值结果是它是负的NaN( -nan
)在我的情况下是完全可以接受的。
After printing the value of x
, it turned out it's negative NaN (-nan
) which is totally acceptable in my case.
尝试使用事实上, NaN!= NaN
并使用 assert(x == x)
After trying to use the fact that NaN != NaN
and using assert(x == x)
, the compiler does me a 'favor' and optimises the assert away.
使自己的 isNaN
函数也被优化。
Making my own isNaN
function is being optimised away as well.
如何检查NaN 和 -NaN是否相等?
How can I check for both equality of NaN and -NaN?
推荐答案
这是令人尴尬的。
编译器(在这种情况下是GCC)优化掉比较的原因和 isnan
返回
false
是因为我团队中的某个人已打开 -ffast-math
。
The reason the compiler (GCC in this case) was optimising away the comparison and isnan
returned false
was because someone in my team had turned on -ffast-math
.
从文档:
-ffast-math
Sets -fno-math-errno, -funsafe-math-optimizations,
-fno-trapping-math, -ffinite-math-only, -fno-rounding-math, -fno-signaling-nans and fcx-limited-range.
This option causes the preprocessor macro __FAST_MATH__ to be defined.
This option should never be turned on by any -O option since it can result in incorrect output for programs which depend on an exact implementation of IEEE or ISO rules/specifications for math functions.
请注意结束句子 - -ffast-math
是不安全的。
Notice the ending sentence - -ffast-math
is unsafe.
这篇关于负NaN不是NaN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!