使用numpy.int32时的浮点近似

Abh*_*jit 2 python floating-point int numpy

回答一个问题为什么scipy.stats.nanmean会给出numpy.nansum不同的结果?,我意识到,乘以numpy.int32float相比一个Python POD在不同float结果结果intfloat.

使用时是否有理由引起浮点近似 numpy.int32

>>> numpy.int32(1) * 0.2
0.20000000000000001
>>> 1 * 0.2
0.2
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 5

这两个表达式给出了值相同但具有不同类型的结果:

In [17]: numpy.int32(1) * 0.2 == 1 * 0.2
Out[17]: True

In [18]: type(numpy.int32(1) * 0.2)
Out[18]: numpy.float64

In [19]: type(1 * 0.2)
Out[19]: float
Run Code Online (Sandbox Code Playgroud)

不同的输出纯粹是由于numpy.float64和之间的默认格式的不同float.

如果我们反转类型,输出也会反转:

In [12]: float(numpy.int32(1) * 0.2)
Out[12]: 0.2

In [13]: numpy.float64(1 * 0.2)
Out[13]: 0.20000000000000001
Run Code Online (Sandbox Code Playgroud)

这纯粹是一个显示问题.这里没有数字差异.