在numpy数组上使用inplace操作时生成的TypeError?

Aae*_*Aae 16 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
Run Code Online (Sandbox Code Playgroud)

我收到此错误消息:

TypeError: ufunc 'add' output (typecode 'O') could not be coerced to provided
output parameter (typecode 'd') according to the casting rule ''same_kind''
Run Code Online (Sandbox Code Playgroud)

如果我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)

先感谢您.

Pie*_* GM 14

当你这样做的时候c=c/2**63,c就会得到dtype=object(这就是问题),同时b留下来dtype=float.

dtype=object向a 添加数组时dtype=float,结果为dtype=object数组.可以把它想象为dtype优先级,就像将numpy浮点数添加到numpy int时给出一个numpy浮点数.

如果您尝试添加objectfloat 的地方,它失败了,因为结果不能从被投objectfloat.但是,当您使用类似的基本添加时b=b+c,结果b将转换为a dtype=object,您可能已经注意到了.

请注意,使用c=c/2.**63keep c作为float并按b+=c预期工作.请注意,如果cnp.ones(1)你会不会有问题,要么.

无论如何:这(np.array([0], dtype=float)/2**63)).dtype == np.dtype(object)可能是一个错误.