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

标签 python numpy floating-point precision type-conversion

下面的代码

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 数字如何用二进制表示的内容。我还没有说得很清楚。

也许有人可以谈谈如何在更一般的范围内获得 float 的精度/分辨率,这对于理解原始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 有。

关于python - 将 int32 转换为其他类型时的精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38592794/

相关文章:

python - 将绘图发送到 flask 中的 html 时出错

Python 多处理池与多处理线程池

python - 检查 NumPy 数组中是否存在值的最有效方法是什么?

floating-point - 从 Julia 中的像素检索 RGB 矢量

objective-c - 获取 float 小数点后的值

c - 高效计算 (a - K)/(a + K) 并提高准确性

python - Pandas 中更快的应用方法

Python:按不区分大小写的字母顺序对元组列表进行排序

Python - 找到2个图的所有交点

python - 使用列表理解创建 numPy 数组