Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

c++ - Why does Release/Debug have a different result for std::min?

Here is the test program:

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;
}

In Debug, I get:

slope is nan
maxThreshold is 1.79769e+308
the_min is nan
the_min is 1.79769e+308

In Release, I get:

slope is nan
maxThreshold is 1.79769e+308
the_min is 1.79769e+308
the_min is nan

Why would I get a different result in Release than Debug?

I already checked Stack Overflow post Use of min and max functions in C++, and it does not mention any Release/Debug differences.

I am using Visual Studio 2015.

question from:https://stackoverflow.com/questions/39919069/why-does-release-debug-have-a-different-result-for-stdmin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In IEEE 754 comparing NAN to anything will always yield false, no matter what it is.

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

And, more importantly for you

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

So it seems that the compiler reorders the parameters/uses > or <= instead of <, and that's why you get the differing results.

For example, those functions could be described as such

Release:

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

Debug:

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

The requirements (LessThanComparable) on std::min aside, those have the same meaning arithmetically. But they yield different results when you use them with NaN.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...