2

I defined a complex matrix of zeros. How I want to generate random numbers in the range (-1/3) to 1/3 as the diagonal elements. How can I do that. I'm getting error that can't convert complex to float. I tried to change data type but still getting this error.

`H = np.reshape(np.zeros((81),dtype=complex),(9,9))
#rf = np.arange(len(rf),dtype=complex)
rf = np.random.uniform(complex(-1./3.),complex(1./3.))`
6
  • Do you want a uniform distribution over the real axis? Thus, no imaginary part added to the numbers? Commented Aug 13, 2019 at 10:05
  • The off diagonal elements of H are complex. So is it compulsory to add imaginary part in rf? Commented Aug 13, 2019 at 10:09
  • I want to generate random numbers from -1/3 to 1/3 along the diagonal. Commented Aug 13, 2019 at 10:09
  • And these will be real numbers, i.e., without an imaginary component? Commented Aug 13, 2019 at 10:10
  • Ok.so it means I need to add imaginary part. No matter if it is zero.right? Commented Aug 13, 2019 at 10:15

1 Answer 1

1

np.random.uniform() does not work with complex numbers, only reals (i.e. floats). However, as long as you only want real numbers along the main diagonal, you can freely assign floats to a complex matrix and they will automatically be converted with the imaginary part being zero:

H = np.zeros((9,9), dtype=np.complex)
rf = np.random.uniform(-1/3, 1/3, 9)
np.fill_diagonal(H, rf)

If you do want an imaginary part as well, you can create two sets of random numbers and then add them together (as the real and imaginary numbers lay on orthogonal axes, they won't "interfere" with eachother

H = np.zeros((9,9), dtype=np.complex)
rf = np.random.uniform(-1/3, 1/3, 9) + 1j*np.random.uniform(-1/3, 1/3, 9)
np.fill_diagonal(H, rf)

As a side not, also look at how you do not need to create your all zeros matrix as a one-dimensional structure and then reshape it. np.zeros() accepts multiple dimensions if it is passed a tuple rather than a number.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.