-1

As per java doc, the Long.MIN_VALUE is -2^63 and Long.MAX_VALUE is 2^63 - 1.

But Long.MIN_VALUE actual value is -2^63 - 1 and Long.MAX_VALUE value is 2^63 if I compute it like here:

long min = -(long) Math.pow(2, 63);
long max = (long) Math.pow(2, 63) - 1;

System.out.println(min);
System.out.println(max);

Over all the range between minimum and maximum value is the same but the actual values are not. Is my understanding of the above code wrong?

My bad, its the way I checked that lead to wrong values. The following is the simplest way I could think of to verify 2 power values in java.

long num = 1;
for(long count = 0; count < 63; count ++) {
    num = num * 2;
}
System.out.println(num);
}
Annapoorni D
  • 831
  • 2
  • 13
  • 30
  • 1
    `long max = (long) (Math.pow(2, 63) - 1), min = max + 1;` – Elliott Frisch Oct 20 '17 at 13:25
  • `double` can only exactly represent integer values up to `2^53 - 1`, and down to `-2^53`. – Andy Turner Oct 20 '17 at 13:29
  • Apart from the 'pow is a double', if the MAX value is `2⁶³-1`, the result of `Math.pow(2, 63)` would overflow the calculation. – M. le Rutte Oct 20 '17 at 13:31
  • 2
    *"Is my above code understanding is wrong?"*; that would be yes –  Oct 20 '17 at 13:33
  • 1
    I'm not convinced about the `duplicate` mark here. They both have the same answer because the reason is the same but the question itself is **different** (*"This question has been asked before [...]"*). I found some meta-posts which suggest to not mark as duplicate. But also not enough to be convinced. – Zabuzard Oct 20 '17 at 13:39

1 Answers1

0

Math.pow's return value is double.

double can only exactly represent all integer values up to 2^53 - 1, and down to -2^53, because it only has 53 mantissa bits.

The error is simply in how you are attempting to check these values.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • This answer is incorrect. `2^53` as upper bound is correct in the general case, but a double absolutely can store the number `2 ^ 63`. The error in the question stems from `-(long) Math.pow(2, 63)` vs `(long) -Math.pow(2, 63)`. – Clashsoft Oct 20 '17 at 14:02