I have a list of complex values that displays the complex amplitudes for a wave function. Each value, real and imaginary, is randomly generated in [-1,1)
. I need to normalize this list in such a way that the sum of the squares of all complex numbers is (1+0j)
.
My code:
import numpy as np
from random import *
num_qubits = 4
state = np.zeros((2**num_qubits), dtype=np.complex64)
for i in range(2**num_qubits):
state[i] = complex(uniform(-1,1),uniform(-1,1))
state = state / np.sqrt(np.sum(state**2))
print(state)
a = 0
for i in range(len(state)):
a += state[i]**2
print(a) ### should be (1+0j)
My code does not give the desired result: the real and imaginary parts of a tend to 1 and 0, respectively, but do not reach them.
Sample output:
[-0.3697332 -0.0641938j -0.88676226+0.4232571j 0.41884637+0.05547267j
0.29857516-0.10600297j -0.4333445 -0.13364498j 0.4524058 +0.22443457j
0.22225586+0.57373726j -0.6371718 -0.9841412j 0.03181012+0.85295266j
-0.39558408-0.12434599j 0.87118745-0.19153355j 1.0328128 -0.1446039j
-0.52917427+0.76342076j 0.52730054+0.15673561j -0.07593771-0.6453003j
0.09273791-0.45075825j]
(1.0000003097685062-9.316019511373952e-08j)
I need to somehow transform the array state
after it is filled with random complex values so that the value a
(the sum of the squares of the elements state[i]
) takes on the value (1+0j)
Your code works. It is just that you only have equality to machine precision. For example, I just ran your code changing to np.complex128
and the result for a
was
(0.9999999999999999-1.734723475976807e-16j)