Mingw32 std::isnan 与 -ffast-math

问题描述 投票:0回答:2

我正在使用

-ffast-math
选项编译以下代码:

#include <limits>
#include <cmath>
#include <iostream>

int main() {
    std::cout << std::isnan(std::numeric_limits<double>::quiet_NaN() ) << std::endl;
}

我得到 0 作为输出。当我的代码使用

-ffast-math
编译时,如何判断浮点数是否为 NaN?

注意:在 Linux 上,

std::isnan
甚至可以与
-ffast-math
一起使用。

c++ g++ mingw32 fast-math isnan
2个回答
10
投票

由于

-ffast-math
指示 GCC 不要处理
NaN
,因此预计
isnan()
具有未定义的行为。因此,返回
0
是有效的。

您可以使用以下快速替换

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

1
投票

在 Linux 上,gcc 标志

-ffast-math
会破坏
isnan()
isinf()
isfinite()
- 可能还有其他相关功能也被破坏,但我尚未测试过。

将函数/宏括在括号中的技巧也不起作用(即

(isnan)(x)

删除

-ffast-math
有效;-)

© www.soinside.com 2019 - 2024. All rights reserved.