Exercice in the cookook Codercise G.2.1

Hi,
I stuck in this code. The amplitude display is not correct after n=5 steps. Please check the image in the encloser.
image

Here the code:
qml.broadcast(qml.Hadamard, pattern=“single”, wires=range(n_bits))
grover_op_matrix = np.dot(diffusion_matrix(), oracle_matrix(combo))

# Apply Grover operator n times
for _ in range(num_steps-1):
    qml.QubitUnitary(grover_op_matrix, wires=range(n_bits))

I really don’t find the difference. Do I need to round something?
Please give me some clue.

Thanks

Hi @quantumel!

It’s true that the graph is right and the error you get isn’t very indicative of the issue.
The issue here is more conceptual than functional. Notice that you’re not actually applying the Grover operator n times. You’re applying it “num_steps-1” times. My guess is that you’re increasing “num_steps” by one but then subtracting it in the for loop. Why don’t you modify the for loop to actually apply the operator “num_steps” times, and update the value you have for num_steps too?

I hope this helps!

1 Like

Hi,

I’m getting the same graph. I don’t know where I’m going wrong.
Please help.
Thank you!

@qml.qnode(dev)
def grover_circuit(combo, num_steps):
    """Apply the Grover operator num_steps times to the uniform superposition
       and return the state.

    Args:
        combo (list[int]): A list of bits representing the secret combination.
        num_steps (int): The number of iterations of the Grover operator
            our circuit is to perform.

    Returns:
        array[complex]: The quantum state (amplitudes) after repeated Grover
        iterations.
    """
    ##################
    # YOUR CODE HERE #
    ##################
    qml.broadcast(unitary=qml.Hadamard,pattern="single",wires=range(n_bits))
    U = oracle_matrix(combo)
    D = diffusion_matrix()

    for _ in range(my_steps):
        qml.QubitUnitary(U,wires=range(n_bits))
        qml.QubitUnitary(D,wires=range(n_bits))
    return qml.state()


my_steps = 4  # YOUR STEP NUMBER HERE

Hi @Krishna_Bhatia,

I’m hiding your code to avoid spoilers for others.

If you look closely you’ll notice that num_steps is an argument for grover_circuit but you’re not using it. You’re using something else in your code. My hint is that you should use num_steps!

I hope this helps!

1 Like