Why does numeric_limits <T> :: min () return the smallest value?
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 expect to see unpredictable results. 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?
Because min gives the smallest normalized value. You can still have smaller denormalized values (see http://en.wikipedia.org/wiki/Denormalized_number ).
Historical reasons. std::numeric_limits was originally built around the contents of <limits.h> (where you have, for example, INT_MIN ) and <float.h> (where you have, for example, DBL_MIN ). These two files were (I suspect) designed by different people; people making floating points do not need a separate most positive and most negative value, because the most negative is always the negation of the most positive, but they must know the lowest value greater than 0. Unfortunately, the values have the same template for the name, and std::numeric_limits ended by defining the semantics of min differently depending on std::numeric_limits<>::is_integer .
This makes programming templates more inconvenient, do you need to do things like std::numeric_limits<T>::is_integer ? std::numeric_limits<T>::min() : -std::numeric_limits<T>::max() 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 expect.