gpt4 book ai didi

python - 使用 numpy.int32 时的浮点近似

转载 作者:行者123 更新时间:2023-11-28 22:00:37 24 4
gpt4 key购买 nike

回答一个问题 Why does scipy.stats.nanmean give different result from numpy.nansum? ,我意识到,与 float< 的 Python POD int 相比,将 numpy.int32 乘以 float 会产生不同的浮点结果.

在使用 numpy.int32 时是否有导致 float 近似的原因?

>>> numpy.int32(1) * 0.2
0.20000000000000001
>>> 1 * 0.2
0.2

最佳答案

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

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

不同的输出纯粹是由于 numpy.float64float 之间默认格式的不同。

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

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

In [13]: numpy.float64(1 * 0.2)
Out[13]: 0.20000000000000001

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

关于python - 使用 numpy.int32 时的浮点近似,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14475922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com