为什么(长)9223372036854665200d给我9223372036854665216? [英] Why is (long)9223372036854665200d giving me 9223372036854665216?
问题描述
我知道有精确错误的奇怪的东西,但我不能欺骗,
I know about weird stuff with precision errors, but I can't fathom,
为什么(长)9223372036854665200d
给我 9223372036854665216
?
推荐答案
9223372036854665200d
是 double
类型的常量。但是, 9223372036854665200
不适用于 double
,且不会损失精度。 double
只有52位尾数,而有问题的数字需要63位来精确表示。
9223372036854665200d
is a constant of type double
. However, 9223372036854665200
does not fit in a double
without loss of precision. A double
only has 52 bits of mantissa, whereas the number in question requires 63 bits to be represented exactly.
最接近的 double
到 9223372036854665200d
是尾数等于的数字1.1111111111111111111111111111111111111111111110010100
,其指数为63(十进制)。此数字不是 9223372036854665216
(称为 U
)。
The nearest double
to 9223372036854665200d
is the number whose mantissa equals 1.1111111111111111111111111111111111111111111110010100
in binary and whose exponent is 63 (decimal). This number is none other than 9223372036854665216
(call it U
).
如果我们将尾数减去一个缺口到 1.1 ... 0011
,我们得到 9223372036854664192
L
)。
If we decrease the mantissa one notch to 1.1...0011
, we get 9223372036854664192
(call it L
).
原始号码在和
U
,并且比 L $ c $更接近
U
c>
The original number is between L
and U
and is much closer to U
than it is to L
最后,如果你认为尾数的截断应该产生一个以一串零结尾的数字,你说得对。只有它发生在二进制,而不是十进制: U
在base-16是 0x7ffffffffffe5000
和 L
为 0x7ffffffffffe4c00
。
Finally, if you think that this truncation of the mantissa ought to result in a number that ends in a bunch of zeros, you're right. Only it happens in binary, not in decimal: U
in base-16 is 0x7ffffffffffe5000
and L
is 0x7ffffffffffe4c00
.
这篇关于为什么(长)9223372036854665200d给我9223372036854665216?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!