I am compiling the following code with the -ffast-math
option:
我正在用-ffast-math选项编译下面的代码:
#include <limits>
#include <cmath>
#include <iostream>
int main() {
std::cout << std::isnan(std::numeric_limits<double>::quiet_NaN() ) << std::endl;
}
I am getting 0 as output. How can my code tell whether a floating point number is NaN when it is compiled with -ffast-math
?
我得到0作为输出。我的代码如何判断一个浮点数是NaN,它是用- ffastmath编译的?
Note: On linux, std::isnan works even with -ffast-math.
注:在linux上,std::isnan甚至与- ffastmath一起工作。
2 个解决方案
#1
10
Since -ffast-math
instructs GCC not to handle NaN
s, it is expected that isnan()
has an undefined behaviour. Returning 0
is therefore valid.
由于-ffast-math指示GCC不处理NaNs,因此期望isnan()有一个未定义的行为。因此返回0是有效的。
You can use the following fast replacement for isnan()
:
您可以使用以下快速替换isnan():
#if defined __FAST_MATH__
# undef isnan
#endif
#if !defined isnan
# define isnan isnan
# include <stdint.h>
static inline int isnan(float f)
{
union { float f; uint32_t x; } u = { f };
return (u.x << 1) > 0xff000000u;
}
#endif
#2
1
On linux, the gcc flag -ffast-math
breaks isnan()
, isinf()
and isfinite()
- there may be other related functions that are also broken that I have not tested.
在linux上,gcc标志-ffast-math断开isnan()、isinf()和is限性()——可能还有其他与我没有测试过的相关函数。
The trick of wrapping the function/macro in parentheses also did not work (ie. (isnan)(x)
)
用括号括起函数/宏的技巧也不起作用。(isnan)(x))
Removing -ffast-math
works ;-)
删除-ffast-math作品;-)
#1
10
Since -ffast-math
instructs GCC not to handle NaN
s, it is expected that isnan()
has an undefined behaviour. Returning 0
is therefore valid.
由于-ffast-math指示GCC不处理NaNs,因此期望isnan()有一个未定义的行为。因此返回0是有效的。
You can use the following fast replacement for isnan()
:
您可以使用以下快速替换isnan():
#if defined __FAST_MATH__
# undef isnan
#endif
#if !defined isnan
# define isnan isnan
# include <stdint.h>
static inline int isnan(float f)
{
union { float f; uint32_t x; } u = { f };
return (u.x << 1) > 0xff000000u;
}
#endif
#2
1
On linux, the gcc flag -ffast-math
breaks isnan()
, isinf()
and isfinite()
- there may be other related functions that are also broken that I have not tested.
在linux上,gcc标志-ffast-math断开isnan()、isinf()和is限性()——可能还有其他与我没有测试过的相关函数。
The trick of wrapping the function/macro in parentheses also did not work (ie. (isnan)(x)
)
用括号括起函数/宏的技巧也不起作用。(isnan)(x))
Removing -ffast-math
works ;-)
删除-ffast-math作品;-)