Ray Hsu
Ray Hsu

Reputation: 3

How to multiply the complex elements by float numbers in numpy?

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?

Upvotes: 0

Views: 9182

Answers (1)

ali_m
ali_m

Reputation: 74182

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.

Upvotes: 2

Related Questions