Java – why (long) 9223372036854665200d give me 9223372036854665216?

I know the strange things of precision error, but I can't understand it,

Why did the (long) 9223372036854665200d give me 9223372036854665216?

Solution

9223372036854665200d is a constant of type double However, the 9223372036854665200 is not suitable for double without loss of accuracy Double has only 52 bits of mantissa, while the problematic number needs 63 bits to be accurately represented

The nearest double number of 9223372036854665200d is the mantissa of binary, equal to 1.1111111111111111111111110010100, and its exponent is 63 (decimal) This number is 9223372036854665216 (called u)

If we reduce the mantissa to 1.1... 0011, we get 9223372036854694192 (called L)

The original number is between L and u and is closer to u than L

Finally, if you think this truncated mantissa should cause a number to end with a pile of zeros, you are right Only it occurs in binary, not decimal: u in base 16 is 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffff4c00

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>