Stuck in coderexercise I.1.1


I tried to solve the coderexercise I.1.1, but I could not.
I looked at similar topics but still I do not manage to solve it.

My code is below, my function randomly generates real and imaginary parts of alpha and betha until getting numbers that satisfy the equation a’**2+b’**2 = 1

Do you have any clues for me to continue the learning path?

Thanks in advance

def my_normalize_state(alpha, beta):
tiene_longitud1 = False
alpha_real = alpha.real
alpha_imag = alpha.imag

beta_real = beta.real
beta_imag = beta.imag
result = []

while (not tiene_longitud1):
    r_alpha_real = random.uniform (0, alpha_real)
    r_alpha_imag = random.uniform (0, alpha_imag)
    r_beta_real = random.uniform (-1, beta_real)
    r_beta_imag = random.uniform (0, beta_imag)
    new_complex_alpha = complex(r_alpha_real, r_alpha_imag)
    new_complex_beta = complex(r_beta_real, r_beta_imag)
    mod_square_alpha = new_complex_alpha * new_complex_alpha.conjugate() 
    mod_square_beta =  new_complex_beta * new_complex_beta.conjugate()
    longitud = mod_square_alpha + mod_square_beta
    if (longitud == 1):
        tiene_longitud1 = True
        result = np.array([new_complex_alpha, new_complex_beta])

return result

Hey @GKelly , welcome to the forum and thanks for droping by to ask about this codercise. :smiling_face:

If I’m reading this right, in your code you’re generating random α and β and then calculating l = |α|^2+|β|^2 until the result is exactly 1. That’s a very unlikely thing to happen, as you’ve probably noticed from trying to run it. :slight_smile:

Instead, imagine that you have a wave function that looks like |ψ⟩=α|0⟩+β|1⟩, and it holds that |α|^2+|β|^2≠1. What can you do to ‘fix’ this? You can rescale these two coefficients. You use the same scale for both of them and that means the ‘vector’ of the wave function is still ‘in the same direction’, but the norm should be equal to one.
This means you need to find α' and β' for which |α'|^2+|β'|^2=1.

To understand how this works (and how and why you can rescale the coefficients of a wave function like this), it might be best if you took a look at the right side of the Codebook first, go through the mathematics. It will seem very simple to you once it ‘clicks’. :slight_smile: