gpt4 book ai didi

c++ - 负NaN不是NaN吗?

转载 作者:IT老高 更新时间:2023-10-28 12:45:48 31 4
gpt4 key购买 nike

在编写一些测试用例时,一些测试会检查 NaN 的结果。

我尝试使用 std::isnan 但断言失败:

Assertion `std::isnan(x)' failed.

打印 x 的值后,结果是负的 NaN (-nan),这在我的情况下是完全可以接受的。

在尝试使用 NaN != NaN 并使用 assert(x == x) 后,编译器帮了我一个忙并优化了断言离开。

制作我自己的 isNaN 函数也正在被优化掉。

如何检查 NaN -NaN 的相等性?

最佳答案

这很尴尬。

编译器(在本例中为 GCC)优化比较并且 isnan 返回 false 的原因是因为我的团队中有人打开了 -ffast -数学.

来自文档:

-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 是不安全的。

关于c++ - 负NaN不是NaN吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3596622/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com