c++ - 为什么发布/调试对 std::min 有不同的结果?

标签 c++ nan min floating-point-comparison

这是测试程序:

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。

最佳答案

IEEE 754将 NAN 与任何东西进行比较总是会产生 false ,不管它是什么。

slope > 0; // false
slope < 0; // false
slope == 0; // false

而且,对你来说更重要的是

slope < DBL_MAX; // false
DBL_MAX < slope; // false

所以编译器似乎重新排序参数/使用 ><=而不是 < ,这就是为什么你会得到不同的结果。

例如,这些功能可以这样描述

发布:

double const& min(double const& l, double const r) {
    return l <= r ? l : r;
}

调试:

double const& min(double const& l, double const& r) {
    return r < l ? r : l;
}

std::min 上的要求 (LessThanComparable)除此之外,它们在算术上具有相同的含义。但是当您将它们与 NaN 一起使用时,它们会产生不同的结果。

关于c++ - 为什么发布/调试对 std::min 有不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39919069/

相关文章:

java - 为什么 fopen 由于 Android-NDK 应用程序的权限问题而在 native 方法中失败?

matlab - 当您使用 NaN 作为 LIBSVM 的特征值时会发生什么?

Java 计算 double - NaN

php - 在 PHP mysqli 中查找 MIN 值但维护行值

python - 在 Pandas 中寻找局部最小值

c++ - 同步 TCP 日间客户端的用法

c++ - 上证所该向上舍入时向下舍入

c++ - Visual Studio 2013 语法突出显示停止工作

python - Python 中具有 nan 值的数组之间的平均值

python - Bokeh Columnsourcedata 查找最小值和最大值