# How to initialize my circuit with two random complex numbers?

Working through Lab 3 in the Qiskit text, I have been attempting to initialize my one qubit circuit with two random numbers. My first attempt, as directed, is using .initialize function, but I keep getting an error:'Sum of amplitudes-squared does not equal one.'

My code

qc = QuantumCircuit(1)

#Create random initial state
SignChoice=[1,-1]
a=random.choice(SignChoice)*random.random()
b=random.choice(SignChoice)*random.random()
p=complex(a,b)
q=np.sqrt(1-p**2)
initial_state = [p,q]  # Define state |q_0>
qc.initialize(initial_state, 0) # Initialise the 0th qubit in the state initial_state


In attempting to fix this error I have used the code below to see my amplitudes and the sum of their squares and though I can see that rounding may sometimes be an issue, it does often result in exactly 1+0j, which leaves me wondering why it will not initialize!

print(p,q,p**2+q**2)


My second attempt will be with random_statevector, but I have not yet completed it.

You can do it slightly different and then you will have no error. Generate 4 random numbers instead of 2, and set q in the same way as p. Then you can compute the norm of p and q using np.linalg.norm() method and set initial_state to be a list of p and q divided by the norm.

Here's the code fixed:

qc = QuantumCircuit(1)

#Create random initial state
SignChoice = [1,-1]

a=random.choice(SignChoice)*random.random()
b=random.choice(SignChoice)*random.random()
c=random.choice(SignChoice)*random.random()
d=random.choice(SignChoice)*random.random()

p=complex(a,b)
q=complex(c,d)
amplitudes = [p,q]
norm = np.linalg.norm(amplitudes)

initial_state = amplitudes/norm  # Define state |q_0>
qc.initialize(initial_state, 0) # Initialise the 0th qubit in the state initial_state

• The norm! I can't believe I missed that! Thanks! What advantage is there in using save_statevector()? I found I did not need this part and am curious why you took this extra step? @Ohad Commented Aug 11, 2022 at 16:10
• No need in save_statevector(). My bad. I'll delete that.