Is there a standard and/or portable way to represent the smallest negative value (e.g. to use negative infinity) in a C(++) program?
DBL_MIN in float.h is the smalle
Are you looking for actual infinity or the minimal finite value? If the former, use
-numeric_limits<double>::infinity()
which only works if
numeric_limits<double>::has_infinity
Otherwise, you should use
numeric_limits<double>::lowest()
which was introduces in C++11.
If lowest()
is not available, you can fall back to
-numeric_limits<double>::max()
which may differ from lowest()
in principle, but normally doesn't in practice.
As from C++11 you can use numeric_limits<double>::lowest(). According to the standard, it returns exactly what you're looking for:
A finite value x such that there is no other finite value y where
y < x
.
Meaningful for all specializations in whichis_bounded != false
.
Online demo
There are many answers going for -std::numeric_limits<double>::max()
.
Fortunately, they will work well in most of the cases. Floating point encoding schemes decompose a number in a mantissa and an exponent and most of them (e.g. the popular IEEE-754) use a distinct sign bit, which doesn't belong to the mantissa. This allows to transform the largest positive in the smallest negative just by flipping the sign:
The standard doesn't impose any floating point standard.
I agree that my argument is a little bit theoretic, but suppose that some excentric compiler maker would use a revolutionary encoding scheme with a mantissa encoded in some variations of a two's complement. Two's complement encoding are not symmetric. for example for a signed 8 bit char the maximum positive is 127, but the minimum negative is -128. So we could imagine some floating point encoding show similar asymmetric behavior.
I'm not aware of any encoding scheme like that, but the point is that the standard doesn't guarantee that the sign flipping yields the intended result. So this popular answer (sorry guys !) can't be considered as fully portable standard solution ! /* at least not if you didn't assert that numeric_limits<double>::is_iec559
is true */
Floating point numbers (IEEE 754) are symmetrical, so if you can represent the greatest value (DBL_MAX
or numeric_limits<double>::max()), just prepend a minus sign.
And then is the cool way:
double f;
(*((long long*)&f))= ~(1LL<<52);
- std::numeric_limits<double>::max()
should work just fine
Numeric limits