Dear Xanadu,

I am stuck in exercise 3 of I1 of the codebook and I would like to ask for your assistance. My proposed solution is the following:

##########################################################

def measure_state(state, num_meas):

state_conj = np.conj(state);

norma = np.sqrt( np.inner(state, state_conj) );

state_norm = state/norma;

state_conj_norm = state_conj/norma;

prob = np.multiply( state_norm, state_conj_norm );

out = np.random.choice(2, num_meas, p = prob);

return out

##########################################################

and it delivers the following error:

Error: Cannot cast array data from dtype(‘complex128’) to dtype(‘float64’) according to the rule ‘safe’

I have tested this function also with:

##########################################################

import numpy as np

num_meas = 10;

state = np.array([0.5, 0.5]);

out = measure_state(state, num_meas) ;

print(f"measurement = { measure_state(state, num_meas) }")

##########################################################

and the results look right to me. What am I missing? and why does the automatic correction delivers that error?

Thanks for the help and your excellent work

Hi @serbenlo ,

I think you’re understanding the question wrong.

Take a look at the example in the question. np.random.choice will generate an array from the numbers that you tell it to, with the size that you give it and with the probabilities that you say.

The probabilities are the norm squared of each of the components in the state.

Remember that the state you get as input is already normalized. So all you need to do is calculate the norm of each component in the state and square it, and this will give you each probability. In this case the norm can be calculated using `np.abs`

.

I hope this helps! Let me know if you manage to solve it.

Hello Catalina,

thanks for your answer. I see that the given probabilities in exercise I1.3 are normalized, although I implemented the normalization in the function in order to make it work for non-normalized states too.

I found the error in the code. It appears because `np.random.choice`

does not accept complex numbers as probabilities (even if the imaginary part is equal zero). Just the real part of `prob`

should be feed in to `np.random.choice`

.

Thanks for your good work,

serbenlo

I’m glad you managed to find the solution @serbenlo !

Keep up the good work