Search code examples
javatypecasting-operator

Type casting in Java. Double to long


Why the output of System.out.println((long)Math.pow(2,63)); and System.out.println((long)(Math.pow(2,63)-1)); is same in Java?


Solution

  • The output is the same because double does not have enough bits to represent 263 exactly.

    Mantissa of a double has only 52 bits:enter image description here

    This gives you at most 17 decimal digit precision. The value you computed, on the other hand, is 9223372036854775808, so it needs 19 digits to be represented exactly. As the result, the actual representation of 263 is 9223372036854776000:

    • Mantissa is set to 1.0 (1 in front is implied)
    • Exponent is set to 1086 (1024 is implicitly subtracted to yield 63)

    The mantissa of representation of 1 is the same, while the exponent is 1024 for the effective value of zero, i.e. the exponents of the two numbers differ by 63, which is more than the size of the mantissa.

    Subtraction of 1 happens while your number is represented as double. Since the magnitude of minuend is much larger than that of the subtrahend, the whole subtraction operation is ignored.

    You would get the same result after subtracting much larger numbers - all the way to 512, which is 29 (demo). After that the difference in exponent would be less than 52, so you would start getting different results.