Search code examples
pythonarrayscomplex-numbers

Assigning Complex Values to an Int Array in Python


everyone. I want to create a random array with a size of 1x1000 and it will have random integers from 0 to 3. Then I want to assign those numbers in different locations in a 2-D cartesian plane. I use real and imaginary axis as my x and y axis. When I try to assign it to 1j or -1j I have an error message:

TypeError("can't convert complex to float")

Can you help me please?

import numpy as np
from math import *

M = 4
N = 1000

firstsymbols = np.random.randint(M, size=N)
symbols = np.zeros(N)

for i in range(1,N):
    if (firstsymbols[i] == 0):
       symbols[i] = 1
    elif (firstsymbols[i] == 1):
       symbols[i] = 1j
    elif (firstsymbols[i] == 2):
       symbols[i] = -1
    else:
       symbols[i] = -1j

print(symbols)

Solution

  • You can create a numpy array of complex numbers with broadcasting,

    1j * np.arange(10)
    

    Or you can keep a 2D array where the first column is the real part and the second column is the imaginary part.