Search code examples
python-3.xnumpycomplex-numbersnumpy-ufunc

Numpy with complex numbers and +=


I found something strange while working with complex matrices in python using numpy. I'll just make a short example to explain it:

This code is working totally fine:

import numpy as np

a = np.zeros((2, 2))
b = np.array([[1j, 1j], [1j, 2]])

a = a + b

print(a)

with output

[[0.+1.j 0.+1.j]
 [0.+1.j 0.+1.j]]

But if I change the a = a + b to a += b (how I usually do it), it's giving me an error.

import numpy as np

a = np.zeros((2, 2))
b = np.array([[1j, 1j], [1j, 1j]])

a += b

print(a)

with error:

numpy.core._exceptions.UFuncTypeError: Cannot cast ufunc 'add' output from dtype('complex128') to dtype('float64') with casting rule 'same_kind'

Where does this come from? I just want to understand.


Solution

  • This error comes from the fact that numpy is overriding functions. In regular Python, the following two statements are equivalent:

    a = a + b
    a += b
    

    However, with numpy this is not the case. With numpy, it is often very important to distinguish whether a new array is created or the original array is modified.

    When you run a = a + b, what this does is create a new array and store that back in a.

    When you run a += b, what this does is try to modify the original a array with b. However, since a is of type float and b is of type imaginary, this modification is illegal.