Code
- T gate (phase = 1/8)
- Rz(pi/3) (phase = 1/6)
Step-by-step explanation
Gate definitionsh(Hadamard): Creates superposition over the counting register.x(Pauli-X): Flips the ancillaato |1⟩, the eigenstate of both target unitaries.cr(theta): Controlled phase rotation — controlledU(0, 0, theta)applies a phase of e^(i·theta) to |1⟩ on the target when the control is |1⟩.
- Hadamard stage — Place all counting qubits in uniform superposition with
h c. - Controlled-U powers — Apply controlled-U^(2^i) for each counting qubit c[i].
- Inverse QFT — Extract the phase from the counting register.
x a sets the ancilla to |1⟩ — the +1 eigenstate of U(0, 0, theta). Because U(0, 0, theta)|1⟩ = e^(i·theta)|1⟩, each controlled application introduces a phase factor onto the corresponding counting qubit without disturbing the ancilla.
Controlled-U powers
For the T gate example with theta = pi/4:
001.
Inverse QFT
The inv_qft subroutine is the standard n-qubit inverse QFT built from Hadamard gates and controlled phase rotations with negative angles. It transforms the phase-encoded state in the counting register into a computational basis state whose binary value approximates φ.
Expected output
T gate (3 counting qubits, φ = 1/8) The phase 1/8 = 0.001 in binary is exactly representable in 3 bits. The measurement is deterministic:
Rz(pi/3) (7 counting qubits, φ = 1/6)
The phase 1/6 = 0.001010101… in binary is irrational and cannot be represented exactly in 7 bits. The QPE output spreads across nearby representable values:
Increasing the number of counting qubits improves phase precision. With n qubits you can resolve phases differing by as little as 1/2ⁿ. The T gate example uses 3 qubits because 1/8 is exactly a 3-bit fraction. Rz(pi/3) uses 7 qubits to get closer to the irrational value 1/6.