minimum double value in C/C++

后端 未结 10 1395
天命终不由人
天命终不由人 2020-12-04 08:41

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

相关标签:
10条回答
  • 2020-12-04 09:32

    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.

    0 讨论(0)
  • 2020-12-04 09:33

    A truly portable C++ solution

    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 which is_bounded != false.

    Online demo


    Lots of non portable C++ answers here !

    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:

    Why aren't these portable ?

    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 */

    0 讨论(0)
  • 2020-12-04 09:34

    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);
    
    0 讨论(0)
  • 2020-12-04 09:34
    - std::numeric_limits<double>::max()
    

    should work just fine

    Numeric limits

    0 讨论(0)
提交回复
热议问题