TypeError generated when using inplace operations on numpy arrays?

Aae picture Aae · Sep 25, 2012 · Viewed 12.3k times · Source

If I run the following code:

import numpy as np

b = np.zeros(1)
c = np.zeros(1)
c = c/2**63

print b, c
b += c

I get this error message:

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

If I change b += c to b = b + c, the code runs fine. Why is it so? I am running Python 2.7.2 on RHEL.

NumPy version: 2.0.0.dev-a2a9dfb

GCC version: 4.1.2 20080704 (Red Hat 4.1.2-52)

Thank you in advance.

Answer

Pierre GM picture Pierre GM · Sep 25, 2012

When you do c=c/2**63, c gets casted to dtype=object (that's the problem), while b stays with dtype=float.

When you add a dtype=object array to a dtype=float, the result is a dtype=object array. Think of it as dtype precedence, like when adding a numpy float to a numpy int gives a numpy float.

If you try to add the object to the float in place, it fails, as the result can't be cast from object to float. When you use a basic addition like b=b+c, though, the result b is cast to a dtype=object, as you may have noticed.

Note that using c=c/2.**63 keeps c as a float and b+=c works as expected. Note that if c was np.ones(1) you would wouldn't have a problem either.

Anyhow: the (np.array([0], dtype=float)/2**63)).dtype == np.dtype(object) is likely a bug.