【发布时间】:2017-02-16 13:27:40
【问题描述】:
这是测试程序:
void testFunc()
{
double maxValue = DBL_MAX;
double slope = std::numeric_limits<double>::quiet_NaN();
std::cout << "slope is " << slope << std::endl;
std::cout << "maxThreshold is " << maxValue << std::endl;
std::cout << "the_min is " << std::min( slope, maxValue) << std::endl;
std::cout << "the_min is " << std::min( DBL_MAX, std::numeric_limits<double>::quiet_NaN()) << std::endl;
}
int main( int argc, char* argv[] )
{
testFunc();
return 0;
}
在调试中,我得到:
slope is nan
maxThreshold is 1.79769e+308
the_min is nan
the_min is 1.79769e+308
在发布时,我得到:
slope is nan
maxThreshold is 1.79769e+308
the_min is 1.79769e+308
the_min is nan
为什么我会在 Release 中得到与 Debug 不同的结果?
我已经检查过 Stack Overflow 帖子 Use of min and max functions in C++,它没有提及任何发布/调试差异。
我正在使用 Visual Studio 2015。
【问题讨论】:
-
我认为问题不在于
std::min,而在于std::numeric_limits<double>::quiet_NaN() -
我记得
cl的 64 位版本在发布模式下无法正确处理NaN,但那是在 VS 2008 中。我希望他们从那时起修复它。 -
我不确定
NaN是否适合LessThanComparable -
我想这两种行为都是有效的,因为 nan 的实际表示是实现定义的。你不应该和 nan 比较,即使是另一个 nan。
-
对于 GCC,您可以在编译器上设置
-frounding-math -fsignaling-nans,以确保严格遵守 IEEE 754。这样,它不应该重新排序可能由于 NaN 而改变行为的比较(或任何其他优化)。对于 Visual Studio,/fp:precise似乎是等价的(承诺不会优化诸如 x-x=0 之类的东西)。
标签: c++ nan min floating-point-comparison