Skip to main content
KetQat

Appearance

Lesson 255 min

The quantum Fourier transform

The QFT as a change of basis, its circuit, its cost, and what it can and cannot speed up.

After this lesson you can

  • Define the quantum Fourier transform and relate it to the discrete Fourier transform, including the sign and normalisation conventions of numpy.fft
  • Derive the product representation of QFT|j⟩ and read the circuit off it
  • Build the QFT circuit from Hadamards, controlled phase gates and swaps, and verify it against a matrix built from the definition
  • Count the gates of the exact and approximate QFT and bound the error of the approximate QFT
  • Explain why applying the QFT does not by itself give a speed-up for computing Fourier transforms
  • Predict the QFT output distribution of a periodic state

Read first: Complex numbers and amplitudes, Quantum gates and unitary transformations, Multiple qubits and entanglement, Quantum circuits and simulation, Grover's algorithm

Why a Fourier transform on a quantum computer

The discrete Fourier transform (DFT) turns a sequence into its frequency content. Periodicity in the input becomes sharp peaks in the output, and that is exactly the structure that the famous exponential quantum algorithms exploit: Shor's factoring algorithm finds the period of a modular exponential, and phase estimation reads an eigenvalue out of a periodic phase pattern. The quantum Fourier transform (QFT) performs the DFT on the amplitudes of an nn-qubit state using only O(n2)O(n^2) gates. That sounds like an exponential improvement over the classical fast Fourier transform, which needs O(Nlog⁡N)=O(n2n)O(N\log N) = O(n2^n) operations on a vector of length N=2nN = 2^n. This lesson builds the QFT, counts its cost honestly, and explains why that comparison is misleading on its own.

Definitions and conventions

Let N=2nN = 2^n. The QFT is the unitary defined on basis states by

QFT ∣j⟩=1N∑k=0N−1e2πi jk/N∣k⟩,\mathrm{QFT}\,\ket{j} = \frac{1}{\sqrt N}\sum_{k=0}^{N-1} e^{2\pi i\,jk/N}\ket{k},

and extended linearly, so an arbitrary state ∑jxj∣j⟩\sum_j x_j\ket{j} is mapped to ∑kyk∣k⟩\sum_k y_k\ket{k} with

yk=1N∑j=0N−1xj e2πi jk/N.y_k = \frac{1}{\sqrt N}\sum_{j=0}^{N-1} x_j\, e^{2\pi i\,jk/N}.

Two conventions are hidden in this formula and both cause real bugs.

  • Sign. The QFT uses e+2πijk/Ne^{+2\pi i jk/N}. NumPy's forward transform np.fft.fft uses e−2πijk/Ne^{-2\pi i jk/N}, and its inverse np.fft.ifft uses the plus sign. So the QFT matrix is the inverse FFT, not the forward one.
  • Normalisation. The QFT carries 1/N1/\sqrt N so that it is unitary. NumPy's default puts no factor on fft and 1/N1/N on ifft; passing norm="ortho" gives 1/N1/\sqrt N on both.

Putting the two together: the QFT of a vector x is np.fft.ifft(x, norm="ortho"). In this course, ∣q0q1…qn−1⟩\ket{q_0q_1\dots q_{n-1}} has qubit 0 as the most significant bit, so j=∑l=0n−1jl 2 n−1−lj = \sum_{l=0}^{n-1} j_l\,2^{\,n-1-l} with j0j_0 the leading bit. Amplitude vectors indexed by the integer jj are the same in every convention; only the mapping from integers to wires changes.

Worked example: two qubits

For n=2n = 2 we have N=4N = 4 and e2πi/4=ie^{2\pi i/4} = i. The basis state ∣1⟩=∣01⟩\ket{1} = \ket{01} maps to

QFT∣01⟩=12(∣0⟩+i∣1⟩+i2∣2⟩+i3∣3⟩)=12(∣00⟩+i∣01⟩−∣10⟩−i∣11⟩).\mathrm{QFT}\ket{01} = \tfrac12\big(\ket{0} + i\ket{1} + i^2\ket{2} + i^3\ket{3}\big) = \tfrac12\big(\ket{00} + i\ket{01} - \ket{10} - i\ket{11}\big).

Every outcome has probability 1/41/4. That is general: the QFT of any basis state has a flat magnitude distribution, and all the information sits in the phases.

The product representation

The circuit follows from one observation: the output of QFT∣j⟩\mathrm{QFT}\ket{j} is a product state. Write the output index in binary, k=∑m=0n−1km2 n−1−mk = \sum_{m=0}^{n-1} k_m 2^{\,n-1-m}. Then

e2πi jk/N=∏m=0n−1e2πi jkm2 n−1−m/2n=∏m=0n−1e2πi jkm/2m+1,e^{2\pi i\,jk/N} = \prod_{m=0}^{n-1} e^{2\pi i\,j k_m 2^{\,n-1-m}/2^n} = \prod_{m=0}^{n-1} e^{2\pi i\,j k_m/2^{m+1}},

and the sum over all kk factorises into a sum over each bit km∈{0,1}k_m \in \{0,1\}:

QFT∣j⟩=⨂m=0n−1∣0⟩+e2πi j/2m+1∣1⟩2.\mathrm{QFT}\ket{j} = \bigotimes_{m=0}^{n-1} \frac{\ket{0} + e^{2\pi i\, j/2^{m+1}}\ket{1}}{\sqrt2}.

The phase on output qubit mm depends on j/2m+1j/2^{m+1} modulo 1, which only involves the last m+1m+1 bits of jj. With the binary-fraction notation 0.b1b2…br=∑ibi2−i0.b_1b_2\dots b_r = \sum_i b_i 2^{-i}:

  • output qubit 0 carries the phase e2πi 0.jn−1e^{2\pi i\,0.j_{n-1}}, which depends only on the last input bit;
  • output qubit 1 carries e2πi 0.jn−2jn−1e^{2\pi i\,0.j_{n-2}j_{n-1}};
  • and output qubit n−1n-1 carries e2πi 0.j0j1…jn−1e^{2\pi i\,0.j_0 j_1\dots j_{n-1}}, which depends on every bit.

Check this against the worked example with j=1=012j = 1 = 01_2: qubit 0 gets e2πi 0.12=eiπ=−1e^{2\pi i\,0.1_2} = e^{i\pi} = -1, giving (∣0⟩−∣1⟩)/2(\ket0 - \ket1)/\sqrt2, and qubit 1 gets e2πi 0.012=ie^{2\pi i\,0.01_2} = i, giving (∣0⟩+i∣1⟩)/2(\ket0 + i\ket1)/\sqrt2. Their product is 12(∣00⟩+i∣01⟩−∣10⟩−i∣11⟩)\tfrac12(\ket{00} + i\ket{01} - \ket{10} - i\ket{11}), as before.

The circuit

A Hadamard on a qubit holding bit bb produces (∣0⟩+e2πi 0.b∣1⟩)/2(\ket0 + e^{2\pi i\,0.b}\ket1)/\sqrt2, since e2πi 0.b=(−1)be^{2\pi i\,0.b} = (-1)^b. Controlled phase gates then add the finer binary digits: the gate Rk=P(2π/2k)=diag(1,e2πi/2k)R_k = P(2\pi/2^k) = \mathrm{diag}(1, e^{2\pi i/2^k}), controlled by a qubit holding bit bb, multiplies the ∣1⟩\ket1 component by e2πi b/2ke^{2\pi i\,b/2^k}, which appends the digit bb at position kk of the binary fraction.

So the circuit processes wire 0 first: a Hadamard gives it 0.j00.j_0; controlled R2R_2 from wire 1 adds j1j_1; controlled R3R_3 from wire 2 adds j2j_2; and so on up to RnR_n, leaving 0.j0j1…jn−10.j_0j_1\dots j_{n-1} on wire 0. Wire 1 is treated the same way with one fewer rotation, and so on down to wire n−1n-1, which gets only a Hadamard. Wire 0 now holds the factor that belongs to output qubit n−1n-1, so a final layer of swaps reverses the wire order.

Quantum circuit on 3 wires (q0, q1, q2). step 1: H on q0. step 2: controlled phase π/2, control q1, target q0. step 3: controlled phase π/4, control q2, target q0. step 4: H on q1. step 5: controlled phase π/2, control q2, target q1. step 6: H on q2. step 7: SWAP q0 and q2.q0q1q2HP(π/2)P(π/4)HP(π/2)H
The three-qubit QFT. Each wire gets a Hadamard and controlled phase rotations from the wires below it; the final SWAP reverses the qubit order.

The inverse QFT is the same circuit run backwards with negated angles. Many algorithms skip the swaps and relabel the wires instead, which is fine as long as the code that reads the output knows.

Cost: exact and approximate

The circuit uses nn Hadamards, ∑j=0n−1(n−1−j)=n(n−1)/2\sum_{j=0}^{n-1}(n-1-j) = n(n-1)/2 controlled phase gates and ⌊n/2⌋\lfloor n/2\rfloor swaps, so its size is O(n2)O(n^2). For n=20n = 20 that is 20 Hadamards, 190 controlled phases and 10 swaps.

Many of those rotations are tiny: RkR_k rotates by 2π/2k2\pi/2^k, which for k=20k = 20 is about 6×10−66\times10^{-6} rad. Coppersmith observed that dropping the smallest rotations leaves a transform that is still very close to the QFT (Coppersmith 1994). Keep only the rotations with k≤mk \le m and call the result QFT~m\widetilde{\mathrm{QFT}}_m. A simple bound follows from two facts: a controlled RkR_k differs from the identity by ∣e2πi/2k−1∣≤2π/2k\abs{e^{2\pi i/2^k} - 1} \le 2\pi/2^k in operator norm, and for unitaries the errors of a product add at most linearly (∥UV−U′V′∥≤∥U−U′∥+∥V−V′∥\norm{UV - U'V'} \le \norm{U - U'} + \norm{V - V'}). Each value of kk occurs at most nn times, so

∥QFT−QFT~m∥≤n∑k>m2π2k≤2πn2m.\big\lVert \mathrm{QFT} - \widetilde{\mathrm{QFT}}_m \big\rVert \le n\sum_{k>m}\frac{2\pi}{2^k} \le \frac{2\pi n}{2^m}.

Choosing m=⌈log⁡2n⌉+cm = \lceil\log_2 n\rceil + c makes the error at most 2π/2c2\pi/2^c with only O(nlog⁡n)O(n\log n) gates. The table below shows the exact operator-norm error for n=8n = 8, computed with the exercise's solution, next to the sum of the norms of the dropped rotations.

kept orders mm controlled phases ∥QFT−QFT~m∥\norm{\mathrm{QFT}-\widetilde{\mathrm{QFT}}_m} sum of dropped norms
4 18 1.131 1.201
5 22 0.414 0.417
6 25 0.123 0.123
7 27 0.0245 0.0245
8 28 0 0

The operator norm measures the worst case over all input states. For a specific input, such as the periodic states that occur in Shor's algorithm, the error in the output distribution can be much smaller. Error correction gives a second reason to drop tiny rotations: on fault-tolerant hardware every small-angle rotation must be synthesised from many gates, so fewer and coarser rotations save real resources.

What the QFT does not do

It is tempting to say the QFT computes Fourier transforms exponentially faster than the FFT. It does not, for three reasons.

  1. The input must already be a quantum state. To transform a classical vector of NN numbers, you first have to load it into amplitudes, and a general state preparation needs order NN gates.
  2. The output cannot be read. The result is a vector of NN amplitudes, but one measurement returns one index kk sampled with probability ∣yk∣2\abs{y_k}^2. Estimating all NN magnitudes, let alone the phases, needs order NN repetitions or more.
  3. The comparison counts different things. The O(n2)O(n^2) is a gate count on a state that already exists; the FFT's O(Nlog⁡N)O(N\log N) is the cost of producing every output number.

The QFT is useful when the input is produced by a quantum computation and the question asked needs only a few samples of the output. The standard example is periodicity. Take the uniform superposition over j∈{s,s+r,s+2r,… }j \in \{s, s+r, s+2r, \dots\} with rr dividing NN. Its QFT has non-zero amplitude only on multiples of N/rN/r, each with probability 1/r1/r, whatever the offset ss; the offset only changes phases. For n=5n = 5 and r=4r = 4, measuring after the QFT always returns one of 0,8,16,240, 8, 16, 24. A handful of samples reveals rr, and in Shor's algorithm the periodic state is produced by modular exponentiation, which a quantum computer can do in polynomial time (Shor 1997). The next lesson develops the same idea for phase estimation (Cleve, Ekert, Macchiavello and Mosca 1998).

Checking a QFT in code

The quickest correctness check is against NumPy, with the convention fixed explicitly:

import numpy as np

n = 3
N = 2**n
idx = np.arange(N)
F = np.exp(2j * np.pi * np.outer(idx, idx) / N) / np.sqrt(N)   # rows k, columns j
print(np.allclose(F, np.fft.ifft(np.eye(N), axis=0, norm="ortho")))   # True
print(np.allclose(F, np.fft.fft(np.eye(N), axis=0, norm="ortho")))    # False: opposite sign

The KetQat SDK applies the actual gate sequence and compares it with the DFT column itself (KetQat SDK). Its documentation states its convention explicitly: the same +2πijk/N+2\pi i jk/N sign as this lesson, but with qubit 0 as the least significant bit. Because it lists output amplitudes by integer index, you can compare its output with yours directly:

from ketqat_runner import catalog

record = catalog.run("[email protected]", seed=7, n_qubits=2,
                     input_state="basis", basis_index=1, shots=100)
print(record.result["output_amplitudes"])

This prints [[0.5, 0.0], [0.0, 0.5], [-0.5, 0.0], [0.0, -0.5]]: the worked example above, as [real, imaginary] pairs.

Exercise: build and test the QFT

In qft-circuit-and-dft you write the QFT matrix from the definition, apply the circuit gate by gate to state vectors, count gates for the exact and approximate transform, and compute the approximate-QFT error. The checks compare your matrix with np.fft.ifft(..., norm="ortho"), check that it is not the forward FFT, compare your circuit with the matrix on random states, test the error bound above, test the periodic-state prediction, and compare your output with the SDK product [email protected] for three basis states.

Common mistakes

  • Using np.fft.fft as the reference. It has the opposite sign. Your QFT will look wrong, or a wrong QFT will look right if you flip a sign elsewhere to compensate.
  • Forgetting the swaps (or forgetting that you skipped them). Without them the circuit computes the QFT followed by a bit reversal; the amplitude magnitudes of a basis input still look flat, so magnitude-only tests do not catch it.
  • Mixing bit orders. Qiskit, the KetQat SDK and this course do not all agree on which wire is the most significant bit. Compare amplitude vectors by integer index, and state the convention.
  • Reading the O(n2)O(n^2) as a speed-up for Fourier analysis of data. Loading and reading out cost order NN.
  • Dropping rotations without a budget. The approximate QFT is accurate only if mm grows like log⁡2n\log_2 n plus the number of bits of accuracy you need.

Summary

The QFT is the unitary ∣j⟩↦N−1/2∑ke2πijk/N∣k⟩\ket{j}\mapsto N^{-1/2}\sum_k e^{2\pi i jk/N}\ket k, which in NumPy terms is ifft with orthonormal scaling. Its output on a basis state is a product of single-qubit states whose phases are binary fractions of jj, and that product form gives a circuit of nn Hadamards, n(n−1)/2n(n-1)/2 controlled phases and ⌊n/2⌋\lfloor n/2\rfloor swaps. Dropping rotations below order m≈log⁡2n+cm \approx \log_2 n + c reduces the gate count to O(nlog⁡n)O(n\log n) with error at most 2π/2c2\pi/2^c. The QFT does not make Fourier analysis of classical data fast; it is a component that turns a periodic quantum state into a few informative samples, which is what phase estimation, the next lesson, relies on.

Exercises

Run these on your own computer. Each comes with automated checks: python -m pytest test_exercise.py. Nothing you write is sent to KetQat.

The QFT as a matrix, a circuit and an approximation

intermediate · about 50 min · needs numpy, pytest, ketqat[algorithms]

Build the quantum Fourier transform twice, once from its definition and once gate by gate, and make the two agree with each other, with NumPy's FFT and with the KetQat SDK.

Convention: QFT∣j⟩=N−1/2∑ke+2πijk/N∣k⟩\mathrm{QFT}\ket{j} = N^{-1/2}\sum_k e^{+2\pi i jk/N}\ket{k}, and qubit 0 is the most significant bit of the basis index.

Functions to implement in starter.py

Function Contract
qft_matrix(n) the N×NN\times N matrix with entry e2πijk/N/Ne^{2\pi i jk/N}/\sqrt N in row kk, column jj
apply_qft_circuit(state, n, max_rotation_order=None) for j=0..n−1j = 0..n-1: H on qubit jj, then for k=2..n−jk = 2..n-j a controlled P(2π/2k)P(2\pi/2^k) with control j+k−1j+k-1 and target jj; finally swap qubit jj with n−1−jn-1-j for j<n/2j < n/2. With max_rotation_order=m, skip rotations with k>mk > m.
qft_gate_counts(n, max_rotation_order=None) {"h": ..., "cp": ..., "swap": ...} for that circuit
circuit_operator(n, max_rotation_order=None) the circuit's matrix, column jj = circuit applied to ∣j⟩\ket{j}
aqft_operator_error(n, m) spectral norm ∥QFT−QFT~m∥2\lVert \mathrm{QFT} - \widetilde{\mathrm{QFT}}_m \rVert_2
periodic_state(n, period, offset=0) uniform superposition over offset, offset + period, ... < 2**n

The helpers _apply_h, _apply_cphase and _apply_swap are provided; they apply one gate to a state vector in the course's bit order.

What the checks verify

  • Your matrix is unitary and equals np.fft.ifft(np.eye(N), axis=0, norm="ortho"), and it is the complex conjugate of the forward np.fft.fft (sign convention).
  • Your circuit equals the matrix on seeded random states for n≤6n \le 6.
  • Gate counts: nn Hadamards, n(n−1)/2n(n-1)/2 controlled phases, ⌊n/2⌋\lfloor n/2\rfloor swaps, and the right count when rotations are dropped.
  • The approximate-QFT error never exceeds the sum of the norms of the dropped rotations, does not grow as you keep more rotations, and vanishes for m=nm = n.
  • A periodic state with period 4 on 5 qubits transforms to outcomes {0,8,16,24}\{0, 8, 16, 24\}, each with probability 1/41/4, for every offset.
  • For three basis states, your circuit output equals the output_amplitudes of the SDK product [email protected]. The SDK uses the opposite bit order (qubit 0 least significant) but lists amplitudes by integer index, so the comparison is convention-free. This check is skipped if the SDK is not installed.

Run the checks

python -m pytest test_exercise.py
Terminal
python -m pip install numpy pytest "ketqat[algorithms]"

starter.py

Python
"""Starter: the quantum Fourier transform as a matrix and as a circuit.

Convention (the course's): QFT|j> = N^{-1/2} sum_k exp(+2 pi i j k / N) |k>, and in
|q_0 q_1 ... q_{n-1}> qubit 0 is the MOST significant bit of the basis index.
"""

import math

import numpy as np


def qft_matrix(n):
    """Dense N x N QFT matrix with entries exp(2 pi i j k / N) / sqrt(N) (row k, column j)."""
    raise NotImplementedError


def _apply_h(state, n, q):
    psi = state.reshape([2] * n)
    a = np.take(psi, 0, axis=q)
    b = np.take(psi, 1, axis=q)
    out = np.stack([(a + b) / math.sqrt(2), (a - b) / math.sqrt(2)], axis=q)
    return out.reshape(-1)


def _apply_cphase(state, n, c, t, angle):
    idx = np.arange(2**n)
    both = ((idx >> (n - 1 - c)) & 1) & ((idx >> (n - 1 - t)) & 1)
    out = state.copy()
    out[both == 1] *= np.exp(1j * angle)
    return out


def _apply_swap(state, n, a, b):
    psi = state.reshape([2] * n)
    return np.swapaxes(psi, a, b).reshape(-1)


def apply_qft_circuit(state, n, max_rotation_order=None):
    """Apply the QFT gate sequence to `state` and return the new vector.

    For qubit j = 0..n-1: H on j, then for k = 2..n-j a controlled phase
    P(2 pi / 2^k) with control qubit j+k-1 and target j. Finally swap qubit j with
    qubit n-1-j for j < n/2. If `max_rotation_order` m is given, controlled phases
    with k > m are skipped (the approximate QFT).
    """
    raise NotImplementedError


def qft_gate_counts(n, max_rotation_order=None):
    """Return {"h": ..., "cp": ..., "swap": ...} for the (approximate) QFT circuit above."""
    raise NotImplementedError


def circuit_operator(n, max_rotation_order=None):
    """The circuit's matrix, built column by column from basis states."""
    raise NotImplementedError


def aqft_operator_error(n, max_rotation_order):
    """Spectral-norm distance between the exact QFT and the approximate circuit."""
    raise NotImplementedError


def periodic_state(n, period, offset=0):
    """Uniform superposition over offset, offset + period, offset + 2 period, ... < 2^n."""
    raise NotImplementedError

test_exercise.py

Python
import importlib.util
import os
from pathlib import Path

def _load_target():
    name = os.environ.get("KETQAT_COMMONS_TARGET", "starter")
    path = Path(__file__).with_name(f"{name}.py")
    spec = importlib.util.spec_from_file_location(f"{Path(__file__).parent.name}_{name}", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

target = _load_target()

import math

import numpy as np
import pytest


def numpy_qft(n):
    """Independent reference: NumPy's inverse FFT with orthonormal scaling uses exp(+2 pi i jk/N)/sqrt(N)."""
    return np.fft.ifft(np.eye(2**n), axis=0, norm="ortho")


@pytest.mark.parametrize("n", [1, 2, 3, 5, 7])
def test_matrix_is_unitary_and_matches_numpy(n):
    F = target.qft_matrix(n)
    assert F.shape == (2**n, 2**n)
    assert np.allclose(F.conj().T @ F, np.eye(2**n), atol=1e-12)
    assert np.allclose(F, numpy_qft(n), atol=1e-12)


def test_sign_convention_is_not_numpys_forward_fft():
    F = target.qft_matrix(3)
    forward = np.fft.fft(np.eye(8), axis=0, norm="ortho")
    assert not np.allclose(F, forward), "the forward np.fft uses exp(-2 pi i jk/N): opposite sign"
    assert np.allclose(F, forward.conj())


@pytest.mark.parametrize("n", [1, 2, 3, 4, 6])
def test_circuit_equals_matrix_on_random_states(n):
    rng = np.random.default_rng(n)
    v = rng.normal(size=2**n) + 1j * rng.normal(size=2**n)
    v /= np.linalg.norm(v)
    assert np.allclose(target.apply_qft_circuit(v, n), numpy_qft(n) @ v, atol=1e-12)


def test_circuit_operator_is_the_qft():
    assert np.allclose(target.circuit_operator(4), numpy_qft(4), atol=1e-12)


@pytest.mark.parametrize("n", [1, 2, 5, 10, 20])
def test_gate_counts(n):
    c = target.qft_gate_counts(n)
    assert c == {"h": n, "cp": n * (n - 1) // 2, "swap": n // 2}


def test_approximate_gate_counts():
    # Keeping rotations up to order m leaves, for target qubit j, min(n-j, m) - 1 rotations.
    n, m = 10, 4
    expected = sum(max(0, min(n - j, m) - 1) for j in range(n))
    assert target.qft_gate_counts(n, m)["cp"] == expected
    assert target.qft_gate_counts(n, n)["cp"] == n * (n - 1) // 2


def test_approximate_qft_error_obeys_the_dropped_rotation_bound():
    n = 6
    errors = []
    for m in range(1, n + 1):
        err = target.aqft_operator_error(n, m)
        # Each dropped controlled rotation P(2 pi/2^k) differs from I by |e^{i 2pi/2^k} - 1| in norm,
        # and norm errors of a product of unitaries add up (triangle inequality).
        bound = sum(abs(np.exp(2j * math.pi / 2**k) - 1) for j in range(n) for k in range(2, n - j + 1) if k > m)
        assert err <= bound + 1e-12
        errors.append(err)
    assert errors[-1] < 1e-12
    assert all(a >= b - 1e-12 for a, b in zip(errors, errors[1:])), "error must not grow when keeping more rotations"


def test_periodic_state_transforms_to_multiples_of_n_over_r():
    n, r = 5, 4
    for offset in range(r):
        out = target.apply_qft_circuit(target.periodic_state(n, r, offset), n)
        probs = np.abs(out) ** 2
        support = np.flatnonzero(probs > 1e-12)
        assert set(support) == {0, 8, 16, 24}
        assert np.allclose(probs[support], 1 / r)


@pytest.fixture
def ketqat_home(tmp_path, monkeypatch):
    monkeypatch.setenv("KETQAT_HOME", str(tmp_path / "ketqat-home"))


@pytest.mark.parametrize("n,j", [(3, 5), (4, 1), (5, 22)])
def test_agrees_with_the_ketqat_sdk(ketqat_home, n, j):
    catalog = pytest.importorskip("ketqat_runner.catalog")
    record = catalog.run("[email protected]", seed=3, n_qubits=n, input_state="basis", basis_index=j, shots=10)
    assert record.status == "succeeded"
    sdk = np.array([complex(re, im) for re, im in record.result["output_amplitudes"]])
    e = np.zeros(2**n, dtype=complex)
    e[j] = 1
    # Amplitudes are listed by integer index, so bit-order conventions do not enter this comparison.
    assert np.allclose(target.apply_qft_circuit(e, n), sdk, atol=1e-9)

Check your understanding

6 questions. Pass with 70% of the points. Answers are checked on the server; retakes are allowed. Explanations appear once you pass or after three complete attempts.

  1. You hold a NumPy vector x of length N=2nN = 2^n. Which expression gives the amplitudes of QFT∑jxj∣j⟩\mathrm{QFT}\sum_j x_j\ket{j} in this course's convention?

    1 pt
  2. In QFT∣j⟩=⨂m=0n−1(∣0⟩+e2πij/2m+1∣1⟩)/2\mathrm{QFT}\ket{j} = \bigotimes_{m=0}^{n-1}(\ket0 + e^{2\pi i j/2^{m+1}}\ket1)/\sqrt2, which input bits does the phase on output qubit 0 depend on?

    1 pt
  3. How many controlled phase gates does the exact QFT circuit on n=20n = 20 qubits use?

    1 pt
  4. Run aqft_operator_error(8, 6) from your qft-circuit-and-dft solution: the spectral-norm distance between the 8-qubit QFT and the approximate QFT that keeps rotations up to order m=6m = 6. (Deterministic; no seed.)

    1 pt

    Computed by running exercise “qft-circuit-and-dft” on your computer.

  5. Why does the O(n2)O(n^2) gate count of the QFT not give an exponentially faster way to Fourier-transform a classical data vector of length N=2nN = 2^n? Select all that apply.

    1 pt

    Select all that apply.

  6. A 6-qubit register holds the uniform superposition over j=3,11,19,…,59j = 3, 11, 19, \dots, 59 (period 8). Which outcomes can you observe after a QFT?

    1 pt

Sign in with GitHub to check answers and save progress. Reading stays free without an account.

References

  1. Don Coppersmith (1994). An approximate Fourier transform useful in quantum factoring. IBM Research Report RC 19642 (posted to arXiv in 2002). arXiv:quant-ph/0201067
  2. Peter W. Shor (1997). Polynomial-time algorithms for prime factorization and discrete logarithms on a quantum computer. SIAM Journal on Computing 26(5), 1484-1509. doi:10.1137/S0097539795293172
  3. Richard Cleve et al. (1998). Quantum algorithms revisited. Proceedings of the Royal Society A 454, 339-354. doi:10.1098/rspa.1998.0164
  4. Michael A. Nielsen, Isaac L. Chuang (2010). Quantum Computation and Quantum Information (10th Anniversary Edition). Cambridge University Press. doi:10.1017/CBO9780511976667
  5. KetQat contributors (2026). KetQat SDK (open source, Apache-2.0), catalog products used at main 2cedabb.