34

Is this the correct way to obtain the most negative double in Java?

double v = -Double.MAX_VALUE;
Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875

2 Answers2

31

Assuming you mean the largest negative, non-infinite number, sounds correct because, for floating point numbers in 64-bit IEEE 754 floating point (which is what Java uses for doubles):

  • The size of the number is stored in one part of the binary rep
  • The sign of the number is stored in a separate part of the binary rep

Therefore: The largest representable negative number would be the same as the largest representable positive number with the sign bit flipped to indicate a negative number.

RHSeeger
  • 16,034
  • 7
  • 51
  • 41
  • Why doesn't (-Double.MAX_VALUE - 1) equal negative infinity, then? – Dean J Mar 05 '10 at 20:10
  • Sorry, my mind is on integers...as was pointed out, floating point does not use two's compliment. – Seth Moore Mar 05 '10 at 20:13
  • How about for case char? Max positive char is 127, but Max negative char is -128, not -127. Is this special case for double? – Cheok Yan Cheng Mar 06 '10 at 04:33
  • It's a special case for float and double, those types that use the IEEE floating point representation under the hood. The various integer types (of which byte can be considered one) use 2s complement. I believe all of them have a "MIN_VALUE" field you can use to get their most negative value. – RHSeeger Mar 06 '10 at 07:00
  • @DeanJ: because they are floats. When you subtract 1 from Double.MAX_VALUE, it is first converted to the MAX_VALUE's exponent, which requires rounding, and in this case, makes the subtrahend 0. – Franz D. Dec 24 '21 at 23:56
24

Nope, it's Double.NEGATIVE_INFINITY.

Sean Owen
  • 66,182
  • 23
  • 141
  • 173
  • How about coment by RHSeegar? – Cheok Yan Cheng Mar 06 '10 at 04:32
  • 4
    Is it a valid double? Yes, it is a well-defined IEEE 754 double value. Double.NEGATIVE_INFINITY is less than -Double.MAX_VALUE, and is by definition <= all doubles (except NaN, which has no ordering). Therefore it is the most negative double, which was the OP question. – Sean Owen Mar 06 '10 at 10:49
  • There are two possible ways to interpret "most negative double". One is negative infinity... the largest possible double. The second is the largest possible representable double, which is what my post describes. – RHSeeger Mar 06 '10 at 18:52
  • 1
    This is a tangent but an interesting one -- why would you not consider negative infinity representable? There definitely is such a double. – Sean Owen Mar 08 '10 at 12:34
  • @RHSeeger, I'd agree if there will be used term "number" instead of "double". But since infinity is one of the values that "double" includes and original question asks for double everything is ok ;) – ony Jan 19 '14 at 21:35