2017-10-07 239 views
0

在這個例子中:python - 爲什麼long和float的乘法會產生小數類似的答案?

long_ten = 10**21 
print(' type(long_ten):', type(long_ten)) 
print('  long_ten: {:52,f}'.format(long_ten)) 
tenth = 0.1 
print(' type(tenth):', type(tenth)) 
print(' float(52f): {:52.52f}'.format(tenth)) 
float_res = tenth * long_ten 
print('\n type(float_res):', type(float_res)) 
print(' float(52f): {:15.52f}'.format(float_res)) 

爲什麼在小數般的精度浮點數長和float結果乘以?

type(long_ten): <type 'long'> 
long_ten:     1,000,000,000,000,000,000,000.000000 
type(tenth): <type 'float'> 
float(52f): 0.1000000000000000055511151231257827021181583404541016 

type(float_res): <type 'float'> 
float(52f): 100000000000000000000.0000000000000000000000000000000000000000000000000000 

我希望的結果是:

100000000000000005551.1151231257827021181583404541016... 

我明白爲什麼結果類型爲浮動 - B/C,它比長

注更寬 - 這是使用Python 2 (如果有的話)

+0

第十位以相對精度丟失 – percusse

回答

0

浮點數只是分母的2次冪的一組分數。2^- nn小數點後的數字,所以一個float可以很容易地有53個非零數字(對於大數字更多,因爲沒有2的冪是10的冪)。你只是打印(幾乎)那個「完整」的數字;我們通常不會那樣做,因爲除了前16個(或其他)之外,其他所有的只是前幾個確定的「噪音」。

2

100000000000000000000可表示爲浮動:

>>> n = 100000000000000000000 
>>> int(float(n)) 
100000000000000000000L 

下一個較大的浮動是100000000000000016384:

>>> from itertools import count 
>>> next(int(float(i)) for i in count(n) if int(float(i)) != n) 
100000000000000016384L 

因此浮最接近您的預期100000000000000005551.115 ......是100000000000000000000,所以這是你得到了什麼。

爲什麼漂浮這個大總是整數?那麼,你可以在二元看到它已經是67位:

>>> bin(n) 
'0b1010110101111000111010111100010110101100011000100000000000000000000' 
>>> len(bin(n)[2:]) 
67 

floats only store the most significant 53 bits。因此,由於前面的位值2 ,所以尾部位已經相當於2 66-52 = 16384.正如我們已經在上面看到的那樣。所以所有的53位都是整數,因此整數也是一個整數。

相關問題