user2250246
user2250246

Reputation: 3967

Confusing long vs double behavior in Java

Here is a small method that shows type-casting to double works, but plain longs do not.

public void test() {
    long s = Long.MIN_VALUE;
    long e = Long.MAX_VALUE;
    System.out.println((double)e-(double)s);
    System.out.println(e-s);
    System.out.println(Double.SIZE);
    System.out.println(Long.SIZE);
}

And the output from the above method is:

1.8446744073709552E19
-1
64
64

So the question is if both double and long are 64-bit numbers in Java, then why does type-casting to double gives a better result?

Follow-up question:

In Java, I want to divide the whole range of long (from -2^63 to 2^63-1) into 10,000 equal ranges. How can I do the same? (some code would be really helpful).

Upvotes: 1

Views: 3524

Answers (1)

Eran
Eran

Reputation: 393781

Long.MAX_VALUE - Long.MIN_VALUE is higher than Long.MAX_VALUE, which is why this subtraction results in numeric overflow. Therefore you don't get the correct result.

The range of numbers represented by the double type is wider, at the price of a lower precision (since some of the bits represent the digits of the number while the rest represent the exponent).

The fact that both long and double types use 64 bits to represent numbers doesn't mean they both support the same range of values. They don't.

The max value that can be represented by a double is 1.7976931348623157E308, while the max value that can be represented by a long is 2^63-1, which is much smaller (9.223372036854776E18).

Upvotes: 4

Related Questions