|
| 1 | +import pennylane as qml |
| 2 | +from pennylane import numpy as np |
| 3 | + |
| 4 | +# Number of qubits in the counting register (controls the precision) |
| 5 | +n_counting = 3 |
| 6 | +dev = qml.device("default.qubit", wires=n_counting + 1) |
| 7 | + |
| 8 | +# Phase to estimate (should be between 0 and 1) |
| 9 | +phi = 0.125 # exact phase is 1/8 |
| 10 | + |
| 11 | +def apply_controlled_unitary(phi, control, target, power): |
| 12 | + """Apply controlled unitary U^{2^power} = Rz(2πφ * 2^power)""" |
| 13 | + angle = 2 * np.pi * phi * (2 ** power) |
| 14 | + qml.ctrl(qml.RZ, control=control)(angle, wires=target) |
| 15 | + |
| 16 | +@qml.qnode(dev) |
| 17 | +def qpe_circuit(): |
| 18 | + # Counting register (first n_counting qubits) |
| 19 | + for i in range(n_counting): |
| 20 | + qml.Hadamard(wires=i) |
| 21 | + |
| 22 | + # Eigenstate |ψ> = |1> on the last qubit |
| 23 | + qml.PauliX(wires=n_counting) |
| 24 | + |
| 25 | + # Apply controlled-U^{2^j} |
| 26 | + for i in range(n_counting): |
| 27 | + apply_controlled_unitary(phi, control=i, target=n_counting, power=n_counting - 1 - i) |
| 28 | + |
| 29 | + # Apply inverse QFT on the counting register |
| 30 | + qml.adjoint(qml.templates.QFT)(wires=range(n_counting)) |
| 31 | + |
| 32 | + # Measurement |
| 33 | + return qml.probs(wires=range(n_counting)) |
| 34 | + |
| 35 | +# Run the circuit |
| 36 | +probs = qpe_circuit() |
| 37 | +estimated_bin = np.argmax(probs) |
| 38 | +estimated_phi = estimated_bin / (2 ** n_counting) |
| 39 | + |
| 40 | +# Print results |
| 41 | +print(f"Exact phase φ: {phi}") |
| 42 | +print(f"Estimated binary outcome: {format(estimated_bin, f'0{n_counting}b')}") |
| 43 | +print(f"Estimated phase φ: {estimated_phi}") |
0 commit comments