Skip to main content
KetQat

Appearance

Lesson 31 h

Quantum phase estimation

Estimating eigenphases with controlled powers and the inverse QFT, with a precision analysis.

After this lesson you can

  • Explain phase kickback and how controlled powers U^(2^k) write an eigenphase into a register
  • Show that the inverse QFT recovers a t-bit phase exactly when the phase is a multiple of 2^-t
  • Derive the outcome distribution for a general phase and prove the 4/π² lower bound for the nearest estimate
  • Choose the number of counting qubits for n bits of precision with success probability at least 1 − ε
  • Predict the output when the input is a superposition of eigenvectors
  • State how order finding, and hence Shor's algorithm, reduces to phase estimation
  • Simulate phase estimation with NumPy and compare it with the KetQat SDK quantum-phase-estimation product

Read first: Quantum gates and unitary transformations, Measurement and probability, Introductory quantum algorithms, The quantum Fourier transform

The task

Let UU be a unitary on some register and ∣u⟩\ket{u} one of its eigenvectors. Because UU is unitary, the eigenvalue has modulus one, so

U∣u⟩=e2πiφ∣u⟩,φ∈[0,1).U\ket{u} = e^{2\pi i\varphi}\ket{u}, \qquad \varphi \in [0, 1).

Phase estimation outputs an estimate of φ\varphi. The task sounds narrow, but much of quantum algorithms reduces to it: energies of a Hamiltonian HH are eigenphases of e−iHte^{-iHt}, and Shor's factoring algorithm is phase estimation applied to a modular multiplication. The method goes back to Kitaev (Kitaev 1995); the form taught here, with an inverse QFT, is the one presented by Cleve, Ekert, Macchiavello and Mosca (Cleve et al. 1998).

We assume three things: you can prepare ∣u⟩\ket{u} (or a state with a large overlap with it, see below), you can apply controlled versions of U2kU^{2^k} for k=0,…,t−1k = 0,\dots,t-1, and you have tt extra "counting" qubits.

Phase kickback

Put a control qubit in ∣+⟩\ket{+} and apply controlled-UU to ∣+⟩∣u⟩\ket{+}\ket{u}:

12(∣0⟩∣u⟩+∣1⟩U∣u⟩)=12(∣0⟩+e2πiφ∣1⟩)∣u⟩.\tfrac{1}{\sqrt2}\big(\ket0\ket u + \ket1 U\ket u\big) = \tfrac{1}{\sqrt2}\big(\ket0 + e^{2\pi i\varphi}\ket1\big)\ket u.

The target is unchanged, and the eigenvalue has moved onto the control as a relative phase. This is the same kickback that turned a bit oracle into a phase oracle in the Foundations lesson on introductory quantum algorithms. With controlled-U2kU^{2^k} the control picks up e2πi 2kφe^{2\pi i\,2^k\varphi} instead.

The circuit

Use tt counting qubits, written ∣c0c1…ct−1⟩\ket{c_0c_1\dots c_{t-1}} with c0c_0 the most significant bit. Apply a Hadamard to each, let counting qubit jj control U2t−1−jU^{2^{t-1-j}}, then apply the inverse QFT to the counting register and measure it. The controlled powers multiply into one phase per basis state: the basis state ∣k⟩\ket{k} of the counting register picks up e2πiφke^{2\pi i\varphi k}, because the bits of kk select which powers were applied, and ∑jcj2t−1−j=k\sum_j c_j 2^{t-1-j} = k. With T=2tT = 2^t, the register is now in

1T∑k=0T−1e2πiφk∣k⟩.\frac{1}{\sqrt T}\sum_{k=0}^{T-1} e^{2\pi i\varphi k}\ket{k}.

The diagram shows a concrete instance with t=3t = 3: U=P(2πφ)U = P(2\pi\varphi) on one qubit, whose eigenvector ∣1⟩\ket1 has eigenphase φ\varphi, so each controlled power is a controlled phase gate.

Quantum circuit on 4 wires (c0, c1, c2, u). step 1: X on u. step 2: H on c0; H on c1; H on c2. step 3: controlled phase 8πφ, control c0, target u. step 4: controlled phase 4πφ, control c1, target u. step 5: controlled phase 2πφ, control c2, target u. step 6: QFT† on c0, c1, c2. step 7: measure c0; measure c1; measure c2.c0c1c2uXHHHP(8πφ)P(4πφ)P(2πφ)QFT†
Phase estimation with three counting qubits for U = P(2πφ) acting on its eigenvector |1⟩. Counting qubit c0 controls U⁴, c1 controls U², c2 controls U; then the inverse QFT and measurement of the counting register.

The exact case

Compare the register state with the QFT from the previous lesson: QFT∣m⟩=T−1/2∑ke2πi mk/T∣k⟩\mathrm{QFT}\ket{m} = T^{-1/2}\sum_k e^{2\pi i\,mk/T}\ket{k}. If φ=m/T\varphi = m/T for an integer mm, the register state is QFT∣m⟩\mathrm{QFT}\ket{m}, so the inverse QFT returns ∣m⟩\ket m with certainty and the measurement reveals all tt bits of φ\varphi. For example, φ=0.3125=5/16\varphi = 0.3125 = 5/16 with t=4t = 4 always yields m=5m = 5, that is 01010101.

The general case

When φ\varphi is not a multiple of 1/T1/T, apply QFT−1\mathrm{QFT}^{-1} and read off the amplitude of ∣m⟩\ket m:

αm=1T∑k=0T−1e2πik(φ−m/T)=1T⋅1−e2πiTδm1−e2πiδm,δm=φ−mT,\alpha_m = \frac1T\sum_{k=0}^{T-1} e^{2\pi i k(\varphi - m/T)} = \frac1T\cdot\frac{1 - e^{2\pi i T\delta_m}}{1 - e^{2\pi i\delta_m}}, \qquad \delta_m = \varphi - \frac mT,

a geometric series. Using ∣1−eix∣=2∣sin⁡(x/2)∣\abs{1 - e^{ix}} = 2\abs{\sin(x/2)},

Pr⁡[m]=∣αm∣2=sin⁡2(πTδm)T2sin⁡2(πδm).\Pr[m] = \abs{\alpha_m}^2 = \frac{\sin^2(\pi T\delta_m)}{T^2\sin^2(\pi\delta_m)}.

This is a Fejér kernel centred on φ\varphi: a peak of width about 1/T1/T around the true phase, with tails falling off like 1/(Tδ)21/(T\delta)^2. Phases are defined modulo 1, so distances are measured on the circle; outcome T−1T-1 is a neighbour of outcome 00.

Theorem (nearest estimate). Let m∗m^\ast be the outcome closest to φT\varphi T on the circle, so ∣δm∗∣≤1/(2T)\abs{\delta_{m^\ast}} \le 1/(2T). Then Pr⁡[m∗]≥4/π2≈0.405\Pr[m^\ast] \ge 4/\pi^2 \approx 0.405.

Proof. Write x=πT∣δm∗∣∈[0,π/2]x = \pi T\abs{\delta_{m^\ast}} \in [0, \pi/2]. On that interval sin⁡x≥2x/π\sin x \ge 2x/\pi, and sin⁡y≤y\sin y \le y for y≥0y \ge 0. Hence Pr⁡[m∗]≥(2x/π)2/(T2(x/T)2)=4/π2\Pr[m^\ast] \ge (2x/\pi)^2 / (T^2 (x/T)^2) = 4/\pi^2. □\square

The bound is approached when φ\varphi lies exactly halfway between two grid points: then the two nearest outcomes share most of the probability almost equally.

Worked example

Take φ=0.3\varphi = 0.3 and t=3t = 3, so T=8T = 8 and φT=2.4\varphi T = 2.4. The nearest outcome is m=2m = 2 (estimate 0.250.25) with δ=0.05\delta = 0.05:

Pr⁡[2]=sin⁡2(0.4π)64sin⁡2(0.05π)=0.90450864×0.0244717≈0.5775.\Pr[2] = \frac{\sin^2(0.4\pi)}{64\sin^2(0.05\pi)} = \frac{0.904508}{64\times0.0244717} \approx 0.5775.

The next outcome, m=3m = 3 (estimate 0.3750.375, δ=−0.075\delta = -0.075), has Pr⁡[3]≈0.2593\Pr[3] \approx 0.2593. Together the two nearest outcomes carry about 84% of the probability. With t=5t = 5 the nearest estimate is 0.31250.3125 with probability 0.57310.5731; with t=8t = 8 it is 77/256≈0.3007877/256 \approx 0.30078 with probability 0.87510.8751. The probability of the nearest outcome does not grow steadily with tt: it depends on where φT\varphi T falls relative to the integer grid.

How many counting qubits

Usually you want nn correct bits, meaning an estimate within 2−n2^{-n} of φ\varphi, with probability at least 1−ε1 - \varepsilon. The trick is to use more counting qubits than bits you want, so that the tails of the Fejér kernel are pushed far away in units of 2−n2^{-n}.

Theorem. With

t=n+⌈log⁡2(2+12ε)⌉t = n + \Big\lceil \log_2\Big(2 + \frac{1}{2\varepsilon}\Big)\Big\rceil

counting qubits, the measured estimate m/Tm/T satisfies ∣m/T−φ∣<2−n\abs{m/T - \varphi} < 2^{-n} (on the circle) with probability at least 1−ε1 - \varepsilon.

Sketch. Let bb be the best tt-bit estimate below φ\varphi. Using ∣sin⁡(πδ)∣≥2∣δ∣\abs{\sin(\pi\delta)} \ge 2\abs\delta for ∣δ∣≤1/2\abs\delta \le 1/2, an outcome at distance ll grid steps from bb has ∣α∣≤1/(2∣l∣)\abs{\alpha} \le 1/(2\abs{l}) or 1/(2∣l−1∣)1/(2\abs{l-1}) depending on the side, and summing the squares of these bounds over ∣l∣>e\abs{l} > e gives a failure probability of at most 1/(2(e−1))1/(2(e-1)). Setting e=2t−n−1e = 2^{t-n}-1 and requiring 1/(2(e−1))≤ε1/(2(e-1)) \le \varepsilon gives the formula. The full argument is in Nielsen and Chuang, section 5.2.1.

For n=4n = 4 and ε=0.05\varepsilon = 0.05: log⁡2(2+10)≈3.58\log_2(2 + 10) \approx 3.58, so t=4+4=8t = 4 + 4 = 8. The extra qubits grow only logarithmically in 1/ε1/\varepsilon. The exercise checks the guarantee numerically on random phases.

Cost, and why the powers matter

The circuit applies UU a total of 1+2+⋯+2t−1=2t−11 + 2 + \dots + 2^{t-1} = 2^t - 1 times if each power is implemented by repetition. Precision 2−t2^{-t} therefore costs order 1/precision1/\text{precision} applications of UU. Compare that with estimating a phase by repeating a single kickback experiment and averaging, which needs order 1/precision21/\text{precision}^2 repetitions to beat shot noise. For phase estimation to be efficient as a function of tt, though, U2kU^{2^k} must be implementable with far fewer than 2k2^k uses of UU. For a general UU it is not, and the cost grows exponentially in the number of bits. For modular multiplication it is, because a2k mod Na^{2^k} \bmod N can be computed by repeated squaring, and this is exactly what makes Shor's algorithm polynomial.

Inputs that are not eigenvectors

If the second register starts in ∑ucu∣u⟩\sum_u c_u\ket{u}, a superposition of eigenvectors with phases φu\varphi_u, linearity gives ∑ucu∣estimate of φu⟩∣u⟩\sum_u c_u\ket{\text{estimate of }\varphi_u}\ket u. Measuring the counting register returns an estimate of φu\varphi_u with probability ∣cu∣2\abs{c_u}^2 and leaves the second register (approximately) in ∣u⟩\ket u. So the outcome distribution is the mixture ∑u∣cu∣2 Pr⁡[m∣φu]\sum_u \abs{c_u}^2\,\Pr[m\mid\varphi_u]. This is how phase estimation can prepare eigenstates and why ground-state energy estimation needs an initial state with a reasonable overlap ∣c0∣2\abs{c_0}^2 with the ground state: the success probability is proportional to it.

Order finding and Shor's algorithm

Here is the connection, stated rather than proved. For coprime integers aa and NN, let rr be the order of aa modulo NN, the smallest r>0r>0 with ar≡1(modN)a^r \equiv 1 \pmod N. The unitary Ua∣y⟩=∣ay mod N⟩U_a\ket{y} = \ket{ay \bmod N} has eigenvectors with eigenphases s/rs/r for s=0,…,r−1s = 0,\dots,r-1, and the easily prepared state ∣1⟩\ket{1} is an equal superposition of them. Phase estimation on ∣1⟩\ket{1} therefore returns an estimate of s/rs/r for a uniformly random ss, and the continued-fraction expansion of a sufficiently precise estimate recovers rr with good probability. Shor showed that the whole procedure, including the controlled modular exponentiation, runs in time polynomial in log⁡N\log N, and that factoring reduces to order finding (Shor 1997). Shor's result is a theorem about ideal quantum circuits; running it at cryptographic size additionally needs a fault-tolerant machine large enough for the arithmetic, a topic for the resource-estimation lesson.

Simulating it

Because the controlled powers only multiply basis states by phases when the target is an eigenvector, the counting-register distribution can be computed directly:

import numpy as np

phi, t = 0.3, 3
T = 2**t
k = np.arange(T)
register = np.exp(2j * np.pi * phi * k) / np.sqrt(T)               # after the controlled powers
inverse_qft = np.exp(-2j * np.pi * np.outer(k, k) / T) / np.sqrt(T)
probs = np.abs(inverse_qft @ register) ** 2
print(np.round(probs, 4))

It prints [0.0216 0.0518 0.5775 0.2593 0.0409 0.0194 0.0145 0.0149], the worked example. The KetQat SDK product simulates the gate sequence and returns the most probable outcome (KetQat SDK):

from ketqat_runner import catalog

record = catalog.run("[email protected]", seed=1, phase=0.3, counting_qubits=5, shots=100)
print(record.result["estimated_phase"], round(record.result["success_probability"], 6))

This prints 0.3125 0.573081. The product assumes an exact eigenstate and does not model the cost of the controlled powers.

Exercise: phase estimation and its precision

In phase-estimation-precision you build the kickback register, the inverse QFT and the outcome distribution, then simulate the whole circuit for an arbitrary unitary, with controlled powers acting on a target register. The checks compare your distribution with the closed form above, confirm the exact dyadic case and the 4/π24/\pi^2 bound on a fine grid of phases, test the counting-qubit formula on random phases, run the full circuit with a seeded random 3×33\times3 unitary, test a superposition of two eigenvectors, and compare your probabilities with the SDK product [email protected].

Common mistakes

  • Wiring the powers in the wrong order. If counting qubit jj controls U2jU^{2^j} instead of U2t−1−jU^{2^{t-1-j}}, the register holds a bit-permuted Fourier state and the inverse QFT no longer recovers the phase: even a dyadic phase gives a spread-out distribution, not simply a bit-reversed answer. Fix the wiring, or apply the inverse QFT without its final swap layer, which undoes the reversal. Test with a dyadic phase, where the correct circuit gives a certain answer.
  • Using the forward QFT at the end. It returns −m mod T-m \bmod T: an estimate of 1−φ1-\varphi.
  • Measuring distance on a line. Phases live on a circle; φ=0.99\varphi = 0.99 is close to the estimate 00.
  • Expecting probability 1 for a non-dyadic phase. Only phases that are multiples of 2−t2^{-t} are recovered with certainty. Otherwise the nearest outcome is guaranteed only 4/π24/\pi^2, and more counting qubits are the remedy.
  • Ignoring the cost of U2kU^{2^k}. Counting qubits are cheap; implementing high powers of UU usually is not.

Summary

Phase estimation writes the eigenphase into a register through kickback from controlled powers U2t−1−jU^{2^{t-1-j}}, producing the state T−1/2∑ke2πiφk∣k⟩T^{-1/2}\sum_k e^{2\pi i\varphi k}\ket k, which the inverse QFT turns into a peak at φT\varphi T. Dyadic phases are recovered exactly. Otherwise the outcome distribution is sin⁡2(πTδ)/(T2sin⁡2(πδ))\sin^2(\pi T\delta)/(T^2\sin^2(\pi\delta)), the nearest estimate has probability at least 4/π24/\pi^2, and t=n+⌈log⁡2(2+1/(2ε))⌉t = n + \lceil\log_2(2 + 1/(2\varepsilon))\rceil counting qubits give nn bits with probability at least 1−ε1-\varepsilon. With a superposition as input, the output is a mixture weighted by the overlaps. Order finding is phase estimation on modular multiplication, which is why Shor's algorithm is efficient when modular exponentiation is. The next module turns to variational methods, starting with the variational quantum eigensolver.

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.

Phase estimation and its precision

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

Simulate quantum phase estimation, first from the kickback state and then as a full circuit with controlled powers of an arbitrary unitary, and test the precision guarantees from the lesson.

Conventions: the counting register ∣c0c1…ct−1⟩\ket{c_0 c_1\dots c_{t-1}} has c0c_0 as the most significant bit, counting qubit jj controls U2t−1−jU^{2^{t-1-j}}, and the QFT uses e+2πijk/Te^{+2\pi i jk/T}, so the inverse QFT carries the minus sign. Phases are in [0,1)[0, 1) and distances between phases are measured on the circle.

Functions to implement in starter.py

Function Contract
inverse_qft_matrix(t) entries e−2πijk/T/Te^{-2\pi i jk/T}/\sqrt T, T=2tT = 2^t
kickback_state(phi, t) T−1/2∑ke2πiφk∣k⟩T^{-1/2}\sum_k e^{2\pi i\varphi k}\ket{k}
qpe_distribution(phi, t) probabilities of outcomes m=0..T−1m = 0..T-1
qpe_with_unitary(U, eigenvector, t) simulate Hadamards, controlled U2t−1−jU^{2^{t-1-j}} and the inverse QFT on the joint register (counting register first); return the counting-register marginal
nearest_estimate_probability(phi, t) probability of the outcome closest to φT\varphi T on the circle
probability_within(phi, t, accuracy) probability that m/Tm/T lies strictly within accuracy of φ\varphi on the circle
counting_qubits_needed(n_bits, epsilon) n+⌈log⁡2(2+1/(2ε))⌉n + \lceil\log_2(2 + 1/(2\varepsilon))\rceil

Hint for qpe_with_unitary: store the joint state as a T×dT\times d array whose row kk is the target-register vector attached to counting value kk. Controlled U2t−1−jU^{2^{t-1-j}} multiplies the rows whose bit jj (counting from the most significant) is 1 by that power.

What the checks verify

  • Your inverse QFT inverts np.fft.ifft(..., norm="ortho").
  • Dyadic phases are recovered with probability 1.
  • Your distribution equals the closed form sin⁡2(πTδ)/(T2sin⁡2(πδ))\sin^2(\pi T\delta)/(T^2\sin^2(\pi\delta)).
  • The nearest outcome has probability at least 4/π24/\pi^2 for 400 phases and three register sizes, and the halfway phase matches the closed-form worst case.
  • With the counting-qubit formula, the estimate lands within 2−n2^{-n} with probability at least 1−ε1-\varepsilon for seeded random phases.
  • The full-circuit simulation with a seeded random 3×33\times3 unitary reproduces the closed form for each eigenvector, and a superposition of two eigenvectors gives the mixture.
  • Your probabilities agree with the SDK product [email protected] (its eight most probable outcomes and its success probability). 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: quantum phase estimation and its precision.

Conventions: the counting register |k> = |k_0 k_1 ... k_{t-1}> has k_0 as the most
significant bit (qubit 0 = MSB, the course convention), and counting qubit j
controls U^(2^(t-1-j)). The QFT is QFT|j> = T^{-1/2} sum_k exp(+2 pi i j k/T)|k>
with T = 2^t, so the inverse QFT carries the minus sign.
"""

import math

import numpy as np


def inverse_qft_matrix(t):
    """Dense inverse QFT on t qubits: entries exp(-2 pi i j k / T) / sqrt(T)."""
    raise NotImplementedError


def kickback_state(phi, t):
    """Counting-register state after the controlled powers: T^{-1/2} sum_k exp(2 pi i phi k) |k>."""
    raise NotImplementedError


def qpe_distribution(phi, t):
    """Probabilities of the outcomes m = 0..2^t - 1 when the eigenphase is phi."""
    raise NotImplementedError


def qpe_with_unitary(U, eigenvector, t):
    """Simulate the whole QPE circuit for a unitary U acting on a d-dimensional target.

    The joint register is counting (t qubits, most significant) tensor target (d levels).
    Returns the marginal distribution of the counting register.
    """
    raise NotImplementedError


def nearest_estimate_probability(phi, t):
    """Probability of the outcome m whose m/2^t is closest to phi on the circle."""
    raise NotImplementedError


def probability_within(phi, t, accuracy):
    """Probability that the estimate m/2^t lies strictly within `accuracy` of phi (circular distance)."""
    raise NotImplementedError


def counting_qubits_needed(n_bits, epsilon):
    """t = n + ceil(log2(2 + 1/(2 epsilon))): n bits of accuracy with probability >= 1 - epsilon."""
    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 fejer(phi, t):
    """Independent closed form: Pr[m] = |sin(pi T delta) / (T sin(pi delta))|^2, delta = phi - m/T."""
    T = 2**t
    out = np.empty(T)
    for m in range(T):
        delta = phi - m / T
        s = math.sin(math.pi * delta)
        out[m] = 1.0 if abs(s) < 1e-15 else (math.sin(math.pi * T * delta) / (T * s)) ** 2
    return out


def test_inverse_qft_inverts_numpys_orthonormal_ifft():
    t = 4
    forward = np.fft.ifft(np.eye(16), axis=0, norm="ortho")  # exp(+2 pi i jk/T)/sqrt(T)
    assert np.allclose(target.inverse_qft_matrix(t) @ forward, np.eye(16), atol=1e-12)


@pytest.mark.parametrize("phi", [0.0, 0.25, 0.3125, 0.6875])
def test_dyadic_phase_is_recovered_with_certainty(phi):
    t = 4
    probs = target.qpe_distribution(phi, t)
    assert np.isclose(probs.sum(), 1)
    assert np.isclose(probs[round(phi * 16) % 16], 1, atol=1e-12)


@pytest.mark.parametrize("phi,t", [(0.3, 5), (0.123, 6), (0.9, 3), (1 / 3, 7)])
def test_distribution_matches_the_closed_form(phi, t):
    assert np.allclose(target.qpe_distribution(phi, t), fejer(phi, t), atol=1e-12)


def test_nearest_estimate_is_at_least_four_over_pi_squared():
    for t in (2, 4, 6):
        for phi in np.linspace(0, 1, 401, endpoint=False):
            assert target.nearest_estimate_probability(phi, t) >= 4 / math.pi**2 - 1e-12


def test_halfway_phase_is_the_worst_case():
    t = 6
    p = target.nearest_estimate_probability((10 + 0.5) / 64, t)
    # At delta = 1/(2T) the closed form gives 1 / (T sin(pi/(2T)))^2, slightly above 4/pi^2.
    assert np.isclose(p, 1 / (64 * math.sin(math.pi / 128)) ** 2, atol=1e-12)


def test_counting_qubits_formula():
    assert target.counting_qubits_needed(4, 0.05) == 8
    assert target.counting_qubits_needed(10, 0.25) == 12


def test_extra_qubits_deliver_the_promised_success_probability():
    rng = np.random.default_rng(5)
    for n_bits, eps in [(3, 0.25), (3, 0.1), (4, 0.05)]:
        t = target.counting_qubits_needed(n_bits, eps)
        for phi in rng.uniform(0, 1, size=25):
            assert target.probability_within(phi, t, 2.0**-n_bits) >= 1 - eps


def test_full_circuit_with_a_random_unitary():
    rng = np.random.default_rng(11)
    z = rng.normal(size=(3, 3)) + 1j * rng.normal(size=(3, 3))
    U, _ = np.linalg.qr(z)
    values, vectors = np.linalg.eig(U)
    for i in range(3):
        phi = (np.angle(values[i]) / (2 * math.pi)) % 1.0
        probs = target.qpe_with_unitary(U, vectors[:, i], 5)
        assert np.allclose(probs, fejer(phi, 5), atol=1e-10)


def test_superposition_of_eigenvectors_mixes_the_distributions():
    # U = diag(1, e^{2 pi i 0.25}); input (|0>+|1>)/sqrt 2 gives outcome 0 and outcome T/4 with 1/2 each.
    U = np.diag([1, np.exp(2j * math.pi * 0.25)])
    probs = target.qpe_with_unitary(U, np.array([1, 1]) / math.sqrt(2), 3)
    expected = np.zeros(8)
    expected[0] = expected[2] = 0.5
    assert np.allclose(probs, expected, atol=1e-12)


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


@pytest.mark.parametrize("phi,t", [(0.3, 5), (0.3125, 4), (0.7071, 6)])
def test_agrees_with_the_ketqat_sdk(ketqat_home, phi, t):
    catalog = pytest.importorskip("ketqat_runner.catalog")
    record = catalog.run("[email protected]", seed=1, phase=phi, counting_qubits=t, shots=10)
    assert record.status == "succeeded"
    probs = target.qpe_distribution(phi, t)
    for row in record.result["top_outcomes"]:
        assert np.isclose(probs[row["integer"]], row["probability"], atol=1e-9)
    assert np.isclose(target.nearest_estimate_probability(phi, t), record.result["success_probability"], atol=1e-9)

Check your understanding

7 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. Phase estimation with t=4t = 4 counting qubits is run on an eigenvector with φ=0.3125\varphi = 0.3125. What is measured?

    1 pt
  2. Using your phase-estimation-precision solution, compute nearest_estimate_probability(0.3, 5). (Deterministic; no seed.)

    1 pt

    Computed by running exercise “phase-estimation-precision” on your computer.

  3. With n=4n = 4 and ε=0.05\varepsilon = 0.05 the formula asks for t=8t = 8 counting qubits. Using your solution, compute probability_within(0.3, 8, 2**-4), the probability that the estimate is within 2−42^{-4} of φ=0.3\varphi = 0.3.

    1 pt

    Computed by running exercise “phase-estimation-precision” on your computer.

  4. How many counting qubits does the formula t=n+⌈log⁡2(2+1/(2ε))⌉t = n + \lceil\log_2(2 + 1/(2\varepsilon))\rceil require for n=6n = 6 bits with failure probability at most ε=0.01\varepsilon = 0.01?

    1 pt
  5. A colleague's phase estimation code ends with the forward QFT instead of the inverse. For φ=0.2\varphi = 0.2 and many counting qubits, what estimate will it report?

    1 pt
  6. The target register starts in 0.7∣u0⟩+0.3∣u1⟩\sqrt{0.7}\ket{u_0} + \sqrt{0.3}\ket{u_1} with eigenphases φ0=0.25\varphi_0 = 0.25 and φ1=0.75\varphi_1 = 0.75, and t=3t = 3. Which statements are true?

    1 pt

    Select all that apply.

  7. 1 pt

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

References

  1. A. Yu. Kitaev (1995). Quantum measurements and the Abelian stabilizer problem. arXiv:quant-ph/9511026
  2. Richard Cleve et al. (1998). Quantum algorithms revisited. Proceedings of the Royal Society A 454, 339-354. doi:10.1098/rspa.1998.0164
  3. 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
  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.