Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does numeric_limits::min return a negative value for int but positive values for float/double?

Why does numeric_limits::min return a negative value for int, but positive values for e.g. float and double?

#include<iostream> #include<limits>  using namespace std;  int main() {   cout << "int: " << numeric_limits<int>::min() << " "        << "float: " << numeric_limits<float>::min() << " "        << "double: " << numeric_limits<double>::min() << "\n";   return 0; } 

Output:

int: -2147483648 float: 1.17549e-38 double: 2.22507e-308 

From cppreference:

Returns the minimum finite value representable by the numeric type T.

For floating-point types with denormalization, min returns the minimum positive normalized value. Note that this behavior may be unexpected, especially when compared to the behavior of min for integral types. To find the value that has no values less than it, use numeric_limits::lowest.

min is only meaningful for bounded types and for unbounded unsigned types, that is, types that represent an infinite set of negative values have no meaningful minimum.

like image 286
gnzlbg Avatar asked Jun 12 '13 16:06

gnzlbg


People also ask

What is Numeric_limits int min ()?

numeric_limits::minReturns the minimum finite value representable by the numeric type T . For floating-point types with denormalization, min returns the minimum positive normalized value. Note that this behavior may be unexpected, especially when compared to the behavior of min for integral types.

Can a float be a negative number?

Yes float can be negative. You can think of float as the gap between EF and LF, or ES and LS. Also Lag and Lead is float.

Can a float be negative Java?

Negative of MAX_VALUE is the mathematical minimum value for floats(same goes for double). The reason you can assume this has to do with how numbers are represented in binary: Java float and doubles use sign bit to represent negative/positive values as opposed to two's complement representation for integers.


1 Answers

By definition, for floating types, min returns the smallest positive value the type can encode, not the lowest.

If you want the lowest value, use numeric_limits::lowest instead.

Documentation: http://en.cppreference.com/w/cpp/types/numeric_limits/min

As for why it is this way, I can only speculate that the Standard committee needed to have a way to represent all forms of extreme values for all different native types. In the case of integral types, there's only two types of extreme: max positive and max negative. For floats there is another: smallest possible.

If you think the semantics are a bit muddled, I agree. The semantics of the related #defines in the C standard are muddled in much the same way.

like image 154
John Dibling Avatar answered Sep 21 '22 15:09

John Dibling