2

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();?

1
  • 3
    You're comparing a number against the minimum of that type to see if it's less than that. That doesn't make sense because if it's less than the minimum, the minimum must be that number and then it's no longer less than the minimum. Commented Mar 27, 2014 at 22:59

2 Answers 2

1

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()?

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, I gathered as much. Im still interested to know why ::min in this case doesnt return what you would expect however. Any idea?
I don't know the exact rationale, but C++ follows what FLT_MIN is set to. I guess it is a matter of minimum floating being an infinity and not a particular finite number.
I guess that makes some sense but it seems slightly misleading with using the term min I guess.
I know. Got bitten by the same problem.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.