简体   繁体   中英

Where do the trailing digits come from when converting a float to an int?

I understand that a float contains a significant amount of digits and the exponent of some base, usually ten. So anything past the significand isn't going to be accurate because nothing was there, but when converting a float to an int (or long), spurious digits appear.

Here's a Python example:

>>> int(1e308)
100000000000000001097906362944045541740492309677311846336810682903157585404911491537163328978494688899061249669721172515611590283743140088328307009198146046031271664502933027185697489699588559043338384466165001178426897626212945177628091195786707458122783970171784415105291802893207873272974885715430223118336L

They don't seem to change when given the same value over and over, so it's probably not completely random or pulled from a mysterious spot in memory. Where do these random digits come from? Just what exactly happens to produce these trailing digits? Why doesn't the conversion simply set the random digits as zero?

They're not random! And the conversion does set all the “random” digits to zero. Just not in base ten!

In Python (2.6 and above), you can call .hex() on any float value to more easily see how it's stored. With 1e308 , you get '0x1.1ccf385ebc8a0p+1023' . On the right you'll see the power of two needed to raise the hexadecimal value on the left for it to be the value entered. In binary the hexadecimal value is 1.00011100110011110011100001011110101111001000101 .

Multiplying it by 2^1023 just shifts the radix point over by 1023 places leaving

1000111001100111100111000010111101011110010001010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

Which is exactly int(1e308) . The conversion from float to integer simply shifts the radix point in base two, and drops the rest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM