Why doesn't numeric_limits<T>::min() return the smallest value?

白昼怎懂夜的黑 提交于 2020-12-25 03:47:34

问题


When I run this code:

#include <limits>
#include <cstdio>

#define T double

int main()
{
    static const T val = std::numeric_limits<T>::min();
    printf( "%g/2 = %g\n", val, val/2 );
}

I would expect to see an unpredictable result. But I get the correct answer:

(16:53) > clang++ test_division.cpp -o test_division
(16:54) > ./test_division 
2.22507e-308/2 = 1.11254e-308

How is this possible?


回答1:


Because min gives you the smallest normalized value. You can still have smaller denormalized values (see http://en.wikipedia.org/wiki/Denormalized_number).




回答2:


Historical reasons. std::numeric_limits was originally built around the contents of <limits.h> (where you have e.g. INT_MIN) and <float.h> (where you have e.g. DBL_MIN). These two files were (I suspect) designed by different people; people doing floating point don't need a separate most positive and most negative value, because the most negative is always the negation of the most positive, but they do need to know the smallest value greater than 0. Regretfully, the values have the same pattern for the name, and std::numeric_limits ended up defining the semantics of min differently depending on std::numeric_limits<>::is_integer.

This makes template programming more awkward, you keep having to do things like std::numeric_limits<T>::is_integer ? std::numeric_limits<T>::min() : -std::numeric_limits<T>::max() so C++11 adds std::numeric_limits<>::lowest(), which does exactly what you'd expect.



来源:https://stackoverflow.com/questions/24829318/why-doesnt-numeric-limitstmin-return-the-smallest-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!