24

This gives the expected result

x = random.rand(1) + random.rand(1)*1j
print x.dtype
print x, x.real, x.imag

and this works

C = zeros((2,2),dtype=complex)
C[0,0] = 1+1j
print C

but if we change it to

C[0,0] = 1+1j + x

I get "TypeError: can't convert complex to float".

If we now omit the explicit dtype = complex, I get "ValueError: setting an array element with a sequence".

Can someone explain what's going on, and how to do this without errors? I'm lost.

4 Answers 4

50

Actually, none of the proposed solutions worked in my case (Python 2.7.6, NumPy 1.8.2). But I've found out, that change of dtype from complex (standard Python library) to numpy.complex_ may help:

>>> import numpy as np
>>> x = 1 + 2 * 1j
>>> C = np.zeros((2,2),dtype=np.complex_)
>>> C
array([[ 0.+0.j,  0.+0.j],
       [ 0.+0.j,  0.+0.j]])
>>> C[0,0] = 1+1j + x
>>> C
array([[ 2.+3.j,  0.+0.j],
       [ 0.+0.j,  0.+0.j]])
0
6

To insert complex x or x + something into C, you apparently need to treat it as if it were an array, so either index into x or assign it to a slice of C:

>>> C
array([[ 0.+0.j,  0.+0.j],
       [ 0.+0.j,  0.+0.j]])
>>> C[0, 0:1] = x
>>> C
array([[ 0.47229555+0.7957525j,  0.00000000+0.j       ],
       [ 0.00000000+0.j       ,  0.00000000+0.j       ]])
>>> C[1, 1] = x[0] + 1+1j
>>> C
array([[ 0.47229555+0.7957525j,  0.00000000+0.j       ],
       [ 0.00000000+0.j       ,  1.47229555+1.7957525j]])

It looks like NumPy isn't handling this case correctly. Consider submitting a bug report.

8
  • but why a=np.arange(4).reshape((2,2)); b=np.array([100]); a[0,0]=b does not give such an error? Feb 25, 2014 at 14:47
  • @zhangxaochen Good Q, maybe the behavior of complex arrays is even buggier than I though. I never use those :)
    – Fred Foo
    Feb 25, 2014 at 15:09
  • Interesting. C[0,0] = random.rand(1) is fine, but C[0,0] = random.rand(1)+random.rand(1)*1j is not. Why does x become an array when we add the imaginary part to it? I thought complex numbers were a native data type in python, not just implemented through arrays?
    – gibson
    Feb 25, 2014 at 18:47
  • @gibson random.rand(1) is an array.
    – Fred Foo
    Feb 25, 2014 at 21:16
  • @larsmans If that's the case, C[0,0] = random.rand(1) shouldn't work, but it does. I'm still confused.
    – gibson
    Feb 26, 2014 at 14:53
2

I used astype to change the type to complex and it worked in my case (Python 3), although I am not sure whether it is the best way. One example:

import numpy as np
c2 = np.empty([2,2]).astype(complex)
c2[0] = 5j+2
0

For example:

x = 1.0
y = 1.5

C[i,j] = complex(x, y)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.