TypeError generated when using inplace operations on numpy arrays?

前端 未结 1 1927
生来不讨喜
生来不讨喜 2021-01-01 11:52

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:

相关标签:
1条回答
  • 2021-01-01 12:28

    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.

    0 讨论(0)
提交回复
热议问题