gpt4 book ai didi

python - 为什么速记赋值和 NaN 有不同的行为?

转载 作者:太空狗 更新时间:2023-10-30 02:21:01 32 4
gpt4 key购买 nike

我在 python 2.7.3 中看到了这一点,同时使用了 pylab 和 numpy。这是为什么:

>>> x = pylab.arange(5)
>>> x = x + pylab.nan
>>> print x
[ nan nan nan nan nan]

不同于此:

>>> x = pylab.arange(5)
>>> x += pylab.nan
__main__:1: RuntimeWarning: invalid value encountered in add
>>> print x
[-9223372036854775808 -9223372036854775808 -9223372036854775808
-9223372036854775808 -9223372036854775808]

?

最佳答案

这是因为 arange(5) 返回一个整数数组,而 nan 是一个浮点值。当您进行常规赋值时,这没问题,因为 x + nan 透明地将 x 转换为 float 以执行加法并返回 float 结果。但是对于 +=,它会尝试将这个 float 结果放回到原来的 x 中,这是一个 int 数组。这失败了,因为 int 数组不能接受 float 数据。

对 numpy 数组使用 += 会在适当的位置更新数组,如果计算结果的数据类型与原始数据类型不同,这将不起作用。

关于python - 为什么速记赋值和 NaN 有不同的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18688178/

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