0
import numpy as np beta= 0.9 A=[1+1j,2+2j] real=np.zeros((1,2)) for i in range(1): for l in range(2): real[i,j] = real[i,j]-beta*A[i,j] 

I am not familiar with the computation of different types of arrays in numpy. How can I make the code work?

1 Answer 1

2

The problem with your original code is that the result of

real[i, j] - beta * A[i, j] 

will be complex, but you created real using np.zeros, which will give you a float64 array unless you explicitly specify a different dtype. Since there is no safe way to cast a complex value to a float, the assignment to real[i, j] will raise a TypeError.

One way to solve the problem would be to initialize real with a complex dtype:

real = np.zeros((1, 2), dtype=np.complex) 

If you make A a numpy array, you can use broadcasting to do the multiplication in one go without pre-allocating real and without looping:

import numpy as np beta = 0.9 A = np.array([1 + 1j, 2 + 2j]) real = -beta * A print(repr(real)) # array([-0.9-0.9j, -1.8-1.8j]) 

It looks like you'd probably benefit from reading some of the examples here.

Sign up to request clarification or add additional context in comments.

1 Comment

@RayHsu: If this answers your question (which it looks to me like it does), please accept it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.