|q⟩ Bad Qubits

intermediate · Programming · The Quantum Fourier Transform

Bit-Reversal and SWAPs

The rotation stage of the QFT circuit — Hadamards plus controlled-phase gates — produces the correct Fourier amplitudes, but it places them in bit-reversed order. The final step of a standard QFT circuit corrects that order with a layer of SWAP gates.

Why the outputs are reversed

Recall the nn-qubit QFT definition for an input j|j\rangle:

QFTnj=12nk=02n1e2πijk/2nk.\mathrm{QFT}_n|j\rangle = \frac{1}{\sqrt{2^n}} \sum_{k=0}^{2^n - 1} e^{2\pi i \, jk / 2^n} |k\rangle.

The rotation circuit builds the output qubit by qubit, starting from the most-significant qubit. The first qubit processed (q0q_0, the most significant) ends up encoding the most-significant bit of the output frequency index kk. The last qubit processed (qn1q_{n-1}, least significant) encodes the least-significant bit of kk. In short, the rotation stage delivers the frequency index in reversed bit order.

For n=3n = 3 the mapping is:

q0k2,q1k1,q2k0q_0 \to k_2, \quad q_1 \to k_1, \quad q_2 \to k_0

where k=4k2+2k1+k0k = 4k_2 + 2k_1 + k_0 in standard binary. To get the natural order (q0k0, q1k1, q2k2q_0 \to k_0,\ q_1 \to k_1,\ q_2 \to k_2) we swap q0q_0 and q2q_2.

The SWAP correction

For nn qubits the correction requires n/2\lfloor n/2 \rfloor SWAPs: swap qubit 00 with qubit n1n-1, qubit 11 with qubit n2n-2, and so on, stopping at the middle.

| nn | SWAPs needed | |-----|-------------| | 2 | 1 (swap qubits 0 and 1) | | 3 | 1 (swap qubits 0 and 2; qubit 1 stays) | | 4 | 2 (swap 0,3 and swap 1,2) |

Each SWAP costs three CNOT gates in hardware, so practitioners sometimes fold the reversal into downstream circuits to avoid paying the cost explicitly. Textbook presentations always include the SWAPs so the QFT matrix matches the classical DFT matrix exactly.

Full 3-qubit QFT

Combining the rotation stage and the SWAP correction gives the complete circuit:

  1. H(q0)H(q_0), CP(π/2,q0,q1)CP(\pi/2, q_0, q_1), CP(π/4,q0,q2)CP(\pi/4, q_0, q_2)
  2. H(q1)H(q_1), CP(π/2,q1,q2)CP(\pi/2, q_1, q_2)
  3. H(q2)H(q_2)
  4. SWAP(q0,q2)\mathrm{SWAP}(q_0, q_2)

This 7-gate sequence implements the exact 8×88 \times 8 QFT unitary.

Try it

The starter code contains the full rotation stage. Add the missing SWAP to put the output in natural bit order. The grader checks the full unitary matrix, so leaving the SWAP out will produce the bit-reversed variant and fail.

Run your code to see the quantum state.

Sign in on the full site to ask questions and join the discussion.