将 int32 转换为其他类型时的精度

Precision when converting int32 to other types

下面的代码

import numpy as np

i = np.iinfo(np.int32).max # 2147483647
x = np.asanyarray(i) # array([2147483647])
dtypes = (np.int32, np.float16, np.float32, np.float64)
for dtp in dtypes:
    print('%s : %s'%(dtp, x.astype(dtp)))

产出

<type 'numpy.int32'> : 2147483647
<type 'numpy.float16'> : inf
<type 'numpy.float32'> : 2147483648.0
<type 'numpy.float64'> : 2147483647.0

现在我们看到 2147483648.0 代表 numpy.float322147483647.0 代表 numpy.float64。我用谷歌搜索并找到 here

All integers with six or fewer significant decimal digits can be converted to an IEEE 754 floating point value without loss of precision, some integers up to nine significant decimal digits can be converted to an IEEE 754 floating point value without loss of precision, but no more than nine significant decimal digits can be stored. As an example, the 32-bit integer 2,147,483,647 converts to 2,147,483,650 in IEEE 754 form.

其中提到了另一个值 2,147,483,650

我不清楚这是怎么发生的。 float32 有效期至 3.402823e38,远远超过最大值 int32。而float64可以给出准确的值。

---------------------------------------------------------------

Emmm.....阅读下面的评论后,我开始阅读更多有关 int 和 float 数字如何用二进制表示的内容。我还没有说得很清楚。

也许有人能说说如何在更一般的范围内得到浮点数的precision/resolution,对理解原Q的问题也有帮助。

print np.finfo(np.float32)
[out]:
Machine parameters for float32
---------------------------------------------------------------
precision=  6   resolution= 1.0000000e-06
machep=   -23   eps=        1.1920929e-07
negep =   -24   epsneg=     5.9604645e-08
minexp=  -126   tiny=       1.1754944e-38
maxexp=   128   max=        3.4028235e+38
nexp  =     8   min=        -max
---------------------------------------------------------------

浮点值由两部分组成,整数和指数。要获得该值,请取 2 的指数次方并将其乘以整数部分。

对于 IEEE 32 位浮点值,整数部分为 only 24 bits long。更大的值可以通过指数补偿得到,但前提是它们的第24位之后的最低位全部为零。

2147483647 的低位没有零,但 2147483648 有。