我知道浮点数包含大量的数字和一些基数的指数,通常为十。因此,通过有效数字的任何东西都不会准确,因为没有任何东西,但是当将float转换为int(或long)时,会出现虚假数字。
这是一个Python示例:
>>> int(1e308)
100000000000000001097906362944045541740492309677311846336810682903157585404911491537163328978494688899061249669721172515611590283743140088328307009198146046031271664502933027185697489699588559043338384466165001178426897626212945177628091195786707458122783970171784415105291802893207873272974885715430223118336L
当一遍又一遍地给出相同的值时,它们似乎没有改变,所以它可能不是完全随机的或从内存中的神秘点拉出来的。这些随机数字来自哪里?究竟是什么产生这些尾随数字?为什么转换只是将随机数设置为零?
答案 0 :(得分:6)
他们不是随意的!并且转换 将所有“随机”数字设置为零。只是不在十点!
在Python(2.6及以上版本)中,您可以在任何浮点值上调用.hex()
,以便更容易地查看它的存储方式。使用1e308
,您获得'0x1.1ccf385ebc8a0p+1023'
。在右侧,您将看到提升左侧十六进制值所需的2的幂,使其成为输入的值。在二进制中,十六进制值为1.00011100110011110011100001011110101111001000101
。
将它乘以2 ^ 1023只会将小数点移动1023个位置
1000111001100111100111000010111101011110010001010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
究竟是int(1e308)
。从float到integer的转换只是简化了基数为2的小数点,然后丢弃其余的小数据。