Python 在numpy阵列上使用就地操作时生成TypeError?
如果我运行以下代码:Python 在numpy阵列上使用就地操作时生成TypeError?,python,arrays,numpy,typeerror,Python,Arrays,Numpy,Typeerror,如果我运行以下代码: import numpy as np b = np.zeros(1) c = np.zeros(1) c = c/2**63 print b, c b += c 我收到以下错误消息: TypeError: ufunc 'add' output (typecode 'O') could not be coerced to provided output parameter (typecode 'd') according to the casting rule ''sa
import numpy as np
b = np.zeros(1)
c = np.zeros(1)
c = c/2**63
print b, c
b += c
我收到以下错误消息:
TypeError: ufunc 'add' output (typecode 'O') could not be coerced to provided
output parameter (typecode 'd') according to the casting rule ''same_kind''
如果我将b+=c
更改为b=b+c
,代码运行正常。为什么会这样?我正在RHEL上运行Python 2.7.2
NumPy版本:2.0.0.dev-a2a9dfb
GCC版本:4.1.2 20080704(Red Hat 4.1.2-52)
提前谢谢。当您执行
c=c/2**63
时,c
将被强制转换为dtype=object
(这就是问题所在),而b
将保持dtype=float
将dtype=object
数组添加到dtype=float
时,结果是一个dtype=object
数组。可以将其视为dtype
优先级,就像将numpy浮点添加到numpy int时,会得到一个numpy浮点
如果您尝试将对象添加到浮动
中,它将失败,因为无法将结果从对象
转换为浮动
。但是,当您使用像b=b+c
这样的基本加法时,结果b
会转换为dtype=object
,您可能已经注意到了这一点
请注意,使用c=c/2.**63
将c
保持为浮点数,b+=c
按预期工作。注意,如果c
是np.ones(1)
你也不会有问题
总之:(np.array([0],dtype=float)/2**63)).dtype==np.dtype(object)
很可能是个bug。请发布你的numpy版本(print np.version.version
)和你的gcc--version
(来自shell),因为我们需要bug报告的信息。我在/
上也有类似的问题。谢谢你的帖子解决了这个问题。我不确定这是个bug。也许——但是2**63
大于int64
的最大值,所以我不确定numpy
除了将其存储在Python对象数组中之外做任何事情都有意义。除了long
的优先级低于float
。是的,我甚至不能重现OPs问题。@senderle有趣的是:你使用的是什么版本的numpy?numpy 1.5.1
。但同样,这种情况也会发生在我身上:>>(np.array([1],dtype=np.float)/np.array([2**63])
=>数组([1.08420217249e-19],dtype=object)
。所以我很不确定现在发生了什么。