Reputation: 4096
While writing some code to ensure user input is valid I came across an issue with std::numeric_limits<T>::min();
where T is a floating point type i.e double/float etc.
Using -std::numeric_limits<double>::max();
allows me to get the real minimum value but you would expect std::numeric_limits<double>::min();
to return that.
Why does std::numeric_limits<double>::min();
not return the smallest possible value of these types and instead force us to use std::numeric_limits::lowest
or -std::numeric_limits<double>::max();
?
Upvotes: 2
Views: 2608
Reputation: 29724
Why is this?
This is because std::numeric_limits<>::min()
returns implementation defined FLT_MIN
, DBL_MIN
or INT_MIN
. In this regard behavior of this method is consistent. But the return value ofstd::numeric_limits<double>::min()
: DBL_MIN
has slightly different meaning than INT_MIN
. This is the smallest value that double
can represent. There might be value greater than 0 but double can't represent it.
why does using min() not do the same thing in this instance?
The rationale behind this is that you can query <limits>
for this value to check for this possible underflow specific to floating point arithmetic.
You can use
std::numeric_limits<double>::lowest()
to query for a lowest negative value.
Upvotes: 0
Reputation: 51465
Yes, using -max()
will give lowest value.
In C++11 there is also std::numeric_limits::lowest
that is consistent for reals and ints.
http://en.cppreference.com/w/cpp/types/numeric_limits/lowest
See also How to workaround the inconsistent definition of numeric_limits<T>::min()?
Upvotes: 1