Skip to main content
KetQat

Appearance

Lesson 255 min

The repetition code

Bit-flip and phase-flip codes, syndromes, decoding and logical error rates.

After this lesson you can

  • Construct the encoding and syndrome-extraction circuits of the three-qubit bit-flip and phase-flip codes
  • Build the syndrome table and the minimum-weight decoder of the d-qubit repetition code
  • Derive the exact logical error rate 3p^2 - 2p^3 and its d-qubit generalisation under code-capacity noise
  • Compute the logical error rate of a memory corrected over many rounds from the per-round rate
  • Simulate code-capacity noise with NumPy and check the estimate against the exact binomial formula and the KetQat SDK
  • Explain why noisy syndrome measurements force decoders to compare syndromes across rounds

Read first: Why quantum error correction works

Where the repetition code fits

The repetition code is the smallest code that shows every moving part of quantum error correction: an encoding, parity checks, a syndrome, a decoder, a logical error rate that falls polynomially with the code size, and a memory experiment that runs for many rounds. It protects against only one kind of error, so it is not a complete quantum code, but it is far from a toy. It is a building block of Shor's nine-qubit code (Shor 1995), and large repetition codes are run on hardware to measure rare error events that smaller experiments cannot see. In this lesson we work through the code exactly, then simulate it.

Throughout, code-capacity noise means: each data qubit independently suffers the error with probability pp, once, and the syndrome is measured perfectly. It is the simplest noise model and the only one for which the answers below are exact.

The three-qubit bit-flip code

The code space is spanned by ∣0L⟩=∣000⟩\ket{0_L} = \ket{000} and ∣1L⟩=∣111⟩\ket{1_L} = \ket{111}. Two CNOTs encode an arbitrary input on q0q_0:

Quantum circuit on 3 wires (q0, q1, q2). step 1: CNOT, control q0, target q1. step 2: CNOT, control q0, target q2.q0q1q2
Bit-flip code: encoding

The parity checks are Z0Z1Z_0Z_1 and Z1Z2Z_1Z_2. Both have eigenvalue +1+1 on every code state, and an XX error on qubit jj flips exactly the checks that contain qubit jj. With s=1s = 1 for eigenvalue −1-1:

Error pattern e=(e0,e1,e2)e = (e_0, e_1, e_2) Syndrome (s1,s2)(s_1, s_2) Decoder applies Net effect
000000 (0,0)(0,0) nothing correct
100100 (1,0)(1,0) X0X_0 correct
010010 (1,1)(1,1) X1X_1 correct
001001 (0,1)(0,1) X2X_2 correct
110110 (0,1)(0,1) X2X_2 X0X1X2X_0X_1X_2: logical flip
011011 (1,0)(1,0) X0X_0 logical flip
101101 (1,1)(1,1) X1X_1 logical flip
111111 (0,0)(0,0) nothing logical flip

Each syndrome is produced by exactly two error patterns, complements of each other: ee and e⊕111e \oplus 111. They differ by the logical operator Xˉ=X0X1X2\bar X = X_0X_1X_2, which commutes with both checks and maps ∣0L⟩\ket{0_L} to ∣1L⟩\ket{1_L}. The decoder cannot tell them apart, so it picks the lighter one, the more likely explanation when p<1/2p < 1/2. This is minimum-weight decoding.

Deriving the logical error rate

The decoder succeeds exactly on the four patterns of weight 0 or 1 and fails on the four of weight 2 or 3. Under code-capacity noise a particular pattern of weight ww has probability pw(1−p)3−wp^w(1-p)^{3-w}, and there are (3w)\binom{3}{w} of them, so

pL=(32)p2(1−p)+(33)p3=3p2−3p3+p3=3p2−2p3.p_L = \binom32 p^2(1-p) + \binom33 p^3 = 3p^2 - 3p^3 + p^3 = 3p^2 - 2p^3.

Worked example. At p=0.05p = 0.05: pL=3(0.0025)−2(0.000125)=0.00725p_L = 3(0.0025) - 2(0.000125) = 0.00725. At p=0.01p = 0.01: pL=2.98×10−4p_L = 2.98\times10^{-4}. The code helps when pL<pp_L < p, that is 3p−2p2<13p - 2p^2 < 1, which holds for all p<1/2p < 1/2 (at p=1/2p = 1/2, pL=1/2p_L = 1/2).

The phase-flip code

Phase errors ZZ are invisible to the bit-flip code. Conjugating by Hadamards exchanges the roles of XX and ZZ, because HXH=ZHXH = Z and HZH=XHZH = X. The phase-flip code uses ∣0L⟩=∣+++⟩\ket{0_L} = \ket{{+}{+}{+}} and ∣1L⟩=∣−−−⟩\ket{1_L} = \ket{{-}{-}{-}}, obtained by appending a Hadamard on every qubit to the bit-flip encoder:

Quantum circuit on 3 wires (q0, q1, q2). step 1: CNOT, control q0, target q1. step 2: CNOT, control q0, target q2. step 3: H on q0; H on q1; H on q2.q0q1q2HHH
Phase-flip code: encoding

Its checks are X0X1X_0X_1 and X1X2X_1X_2, and a ZZ error on qubit jj flips the checks containing jj, so the syndrome table is the one above with XX and ZZ exchanged, and the logical error rate under independent phase flips is again 3p2−2p33p^2 - 2p^3. To measure an XX-type check onto an ancilla, prepare the ancilla in ∣+⟩\ket{+} (Hadamard after reset), use it as the control of CNOTs onto the data, and measure it in the XX basis (Hadamard, then measure):

Quantum circuit on 5 wires (q0, q1, q2, a0, a1). step 1: H on a0; H on a1. step 2: CNOT, control a0, target q0. step 3: CNOT, control a0, target q1. step 4: CNOT, control a1, target q1. step 5: CNOT, control a1, target q2. step 6: H on a0; H on a1. step 7: measure a0; measure a1.q0q1q2a0a1HHHH
Measuring X0X1 and X1X2 with two ancillas

The ancilla picks up a phase (−1)(-1) for each data qubit in ∣−⟩\ket{-}, which the final Hadamard turns into a bit. Compare this with the ZZ-check circuit of the previous lesson, where data qubits are the controls and the ancilla the target. Surface-code circuits use both patterns side by side.

Neither three-qubit code handles both error types. Shor's code concatenates them: three phase-flip blocks, each made of three bit-flip-encoded qubits, correct any single-qubit error. The next lesson describes both codes in one language, the stabilizer formalism.

The dd-qubit repetition code

Using dd qubits (dd odd) with checks ZiZi+1Z_iZ_{i+1} for i=0,…,d−2i = 0, \dots, d-2 gives the distance-dd bit-flip repetition code. The syndrome has d−1d-1 bits, and again each syndrome is shared by exactly two error patterns, ee and its complement. A convenient decoder reconstructs one of them directly from the syndrome: set c0=0c_0 = 0 and ci+1=ci⊕sic_{i+1} = c_i \oplus s_i; if this candidate has weight more than d/2d/2, use its complement. The decoder corrects every pattern of weight at most t=(d−1)/2t = (d-1)/2 and fails on every pattern of weight more than d/2d/2, so

pL(d,p)=∑k=t+1d(dk)pk(1−p)d−k  ≈  (dt+1) pt+1(p≪1).p_L(d, p) = \sum_{k=t+1}^{d} \binom{d}{k} p^k (1-p)^{d-k} \;\approx\; \binom{d}{t+1}\,p^{t+1} \quad (p \ll 1).

This is the formula you will test in the exercise. A few values, computed directly from the sum:

pp d=1d=1 d=3d=3 d=5d=5 d=7d=7 d=9d=9
0.01 1.0×10−21.0\times10^{-2} 2.98×10−42.98\times10^{-4} 9.85×10−69.85\times10^{-6} 3.42×10−73.42\times10^{-7} 1.22×10−81.22\times10^{-8}
0.1 1.0×10−11.0\times10^{-1} 2.80×10−22.80\times10^{-2} 8.56×10−38.56\times10^{-3} 2.73×10−32.73\times10^{-3} 8.91×10−48.91\times10^{-4}
0.3 3.0×10−13.0\times10^{-1} 2.16×10−12.16\times10^{-1} 1.63×10−11.63\times10^{-1} 1.26×10−11.26\times10^{-1} 9.88×10−29.88\times10^{-2}
import math

def p_logical(n, p):
    return sum(math.comb(n, k) * p**k * (1 - p) ** (n - k) for k in range(n // 2 + 1, n + 1))

for p in (0.01, 0.1, 0.3):
    print(p, [f"{p_logical(n, p):.3e}" for n in (1, 3, 5, 7, 9)])

Two things are worth reading off the table. Far below p=1/2p = 1/2, each step d→d+2d \to d+2 multiplies pLp_L by roughly a constant factor (about 30 at p=0.01p = 0.01, about 3 at p=0.1p = 0.1), so pLp_L falls exponentially in dd. Close to p=1/2p = 1/2 the gain per step is small. The distance dd is the smallest number of single-qubit XX errors that produce an undetected logical flip; the code corrects up to t=⌊(d−1)/2⌋t = \lfloor (d-1)/2 \rfloor of them.

The distance against phase errors, however, is 1: a single ZjZ_j acts as the logical Zˉ\bar Z on the bit-flip code. Quantum codes must have large distance against both types at once, which is exactly what the surface code achieves.

The repetition code as a memory

A quantum memory must hold its state for many rounds. Suppose that in every round each qubit flips with probability pp, after which the syndrome is measured perfectly and the decoder's correction applied. Each round is then an independent copy of the experiment above, and the logical bit is flipped at the end of round rr with probability q=pL(d,p)q = p_L(d,p), independently of other rounds. After TT rounds the stored bit is wrong if an odd number of rounds failed:

PT=∑k odd(Tk)qk(1−q)T−k=1−(1−2q)T2,P_T = \sum_{k \text{ odd}} \binom{T}{k} q^k(1-q)^{T-k} = \frac{1 - (1-2q)^T}{2},

using ∑k(Tk)qk(1−q)T−k(±1)k=(1−q∓q)T\sum_k \binom{T}{k}q^k(1-q)^{T-k}(\pm1)^k = (1-q \mp q)^T. For small TqTq this is about TqTq; for large TT it tends to 1/21/2, a completely random bit. Worked example: d=3d = 3, p=0.05p = 0.05, T=10T = 10 gives q=0.00725q = 0.00725 and P10=(1−0.985510)/2≈0.0679P_{10} = \bigl(1 - 0.9855^{10}\bigr)/2 \approx 0.0679. The same formula converts between "per shot" and "per round" logical error rates later in the course.

When the syndrome itself is noisy

Real syndrome measurements fail too. If a check outcome is wrong with probability qmq_m, a decoder that trusts each round's syndrome would apply a spurious correction, creating an error instead of removing one. The remedy is to measure the checks repeatedly and look at changes: define a detection event in round rr as sr⊕sr−1s_r \oplus s_{r-1} for each check. A data error that appears between rounds r−1r-1 and rr changes the syndrome permanently and causes detection events in neighbouring checks in one round; a measurement error in round rr causes detection events in the same check in rounds rr and r+1r+1. Decoding becomes a problem on a two-dimensional space-time grid of detection events, solved by matching in the matching lesson, with circuits built in the Stim lesson. With dd qubits measured over dd rounds, both data errors and measurement errors need about d/2d/2 faults to fool the decoder, so the code keeps its distance in time as well as in space.

Repetition codes are also used on hardware to probe rare, correlated errors. In a published experiment on a superconducting processor, Google Quantum AI ran a distance-25 repetition code and reported a logical error floor of 1.7×10−61.7\times10^{-6} per round, set by a single high-energy event (1.6×10−71.6\times10^{-7} per round when that event was excluded) (Google Quantum AI 2023). These are published values for that device and protocol; we do not reproduce them here.

Simulating code-capacity noise

A Monte Carlo simulation of the code-capacity model needs only NumPy, and the KetQat SDK's repetition-code product provides an independent reference that reports the exact value beside its estimate and a 95% Wilson interval (the interval is explained in the thresholds lesson):

from ketqat_runner import catalog

record = catalog.run("[email protected]", seed=7, n=5, physical_error_rate=0.1, shots=100_000)
r = record.result
print(r["logical_failures"], r["logical_error_rate"])
print(r["confidence_interval"]["lower"], r["confidence_interval"]["upper"])
print(r["exact_logical_error_rate"], r["exact_within_interval"])

With the pinned SDK this prints 829 failures (rate 0.00829), the interval [0.00775,0.00887][0.00775, 0.00887], and the exact value 0.008560.00856, which lies inside it. The run writes a small record under $KETQAT_HOME (default ~/.ketqat).

In the exercise you write your own vectorised simulator: sample a (shots, n) array of flips, compute the syndromes with one XOR, decode them with the running-XOR decoder, and count failures. You then compare against the exact formula, the SDK product and the multi-round formula above. A good habit starts here: never trust a simulation pipeline that has not reproduced a case with a known answer.

Common mistakes

  • Decoding from the error instead of the syndrome. A decoder that looks at the sampled error pattern is not a decoder. Your decoding function should receive only the syndrome.
  • Counting weight-d/2d/2 ties. For even dd some syndromes have two equally light explanations, and majority vote is undefined. Use odd dd, or state how ties are broken.
  • Confusing "per shot" with "per round". A memory of TT rounds that fails with probability PTP_T does not fail with probability PTP_T per round; invert PT=(1−(1−2q)T)/2P_T = (1 - (1-2q)^T)/2.
  • Expecting the bit-flip code to protect against ZZ errors. Its distance for phase errors is 1.
  • Using the code-capacity formula for circuit-level noise. Once measurements and gates are noisy the exact formula no longer applies; it becomes a sanity check for the noiseless-measurement limit only.
  • Comparing two Monte Carlo runs that share a seed. Identical seeds give correlated samples and make differences look more precise than they are.

Summary

  • The bit-flip code measures ZiZi+1Z_iZ_{i+1}, the phase-flip code XiXi+1X_iX_{i+1}; Hadamards map one onto the other.
  • Every syndrome has exactly two explanations, an error and its complement; the minimum-weight decoder picks the lighter one.
  • Under code-capacity noise pL=3p2−2p3p_L = 3p^2 - 2p^3 for three qubits and ∑k>d/2(dk)pk(1−p)d−k\sum_{k>d/2}\binom{d}{k}p^k(1-p)^{d-k} for dd qubits.
  • Over TT independent rounds the logical error is (1−(1−2q)T)/2(1 - (1-2q)^T)/2.
  • Noisy syndrome measurements are handled by repeating them and decoding detection events in space and time.

Next, the stabilizer formalism gives a single language for these codes, for Shor's and Steane's codes and for the surface code. For background reading see Nielsen and Chuang, section 10.1.

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.

Simulating the repetition code against its exact logical error rate

introductory · about 50 min · needs numpy, pytest, ketqat[qec]

You will write a small, vectorised Monte Carlo simulation of the nn-qubit bit-flip repetition code under code-capacity noise (independent bit flips, perfect syndrome measurement), decode it from the syndrome alone, and check the result against the exact binomial formula and against the KetQat SDK's repetition-code product. You then extend it to a memory that is corrected after every round.

Data layout

A batch of errors is a (shots, n) array of 0/1 integers: entry [s, j] = 1 means data qubit j suffered an XX error in shot s. Syndrome bit i (i=0,…,n−2i = 0, \dots, n-2) is the parity of qubits i and i+1, the outcome of ZiZi+1Z_iZ_{i+1}.

Functions to implement in starter.py

Function Contract
exact_logical_error_rate(n, p) ∑k>n/2(nk)pk(1−p)n−k\sum_{k>n/2}\binom{n}{k}p^k(1-p)^{n-k}; ValueError for even n or p outside [0,1][0,1].
syndromes(errors) (shots, n) errors to (shots, n-1) syndromes.
decode_min_weight(syn, n) The minimum-weight correction consistent with each syndrome row, as a (shots, n) array. Work from the syndrome only.
logical_failures(errors, corrections) Boolean per shot, True when error XOR correction is X⊗nX^{\otimes n}; ValueError if a residual is neither all zeros nor all ones.
sample_code_capacity(n, p, shots, seed) Number of failures. Sample exactly as rng = np.random.default_rng(seed), errors = rng.random((shots, n)) < p, so a seed reproduces a number.
exact_memory_failure(n, p, rounds) Probability that the logical bit is flipped after rounds rounds of noise followed by perfect correction: 12(1−(1−2pL)rounds)\tfrac12\bigl(1-(1-2p_L)^{\text{rounds}}\bigr).
sample_memory(n, p, rounds, shots, seed) Monte Carlo of the same memory. One generator; in every round draw rng.random((shots, n)) < p, XOR it into the current error, then correct.

Hint for the decoder: the syndrome fixes the error up to the complement. Fix c0=0c_0 = 0, rebuild ci+1=ci⊕sic_{i+1} = c_i \oplus s_i, and if that candidate is heavier than n/2n/2 take its complement.

What the checks verify

  • pL(3,p)=3p2−2p3p_L(3,p) = 3p^2 - 2p^3, pL(1,p)=pp_L(1,p) = p, and the leading-order behaviour (nt+1)pt+1\binom{n}{t+1}p^{t+1} for small pp with t=(n−1)/2t = (n-1)/2.
  • Every error of weight at most tt is corrected exactly; on all 2n2^n errors for n=3,5n = 3, 5 the correction reproduces the syndrome, is never heavier than its complement, and fails exactly when more than half the qubits flipped.
  • The seeded Monte Carlo agrees with the exact formula within five standard errors, and with an independent sampler, the KetQat SDK repetition-code product, whose exact value must equal yours.
  • The multi-round simulation agrees with the exact memory formula, which tends to 1/21/2 after many rounds.

The SDK check writes a run record into a temporary directory (it sets KETQAT_HOME), so nothing is left behind. It is skipped if ketqat_runner is not installed; install the SDK with pip install "ketqat[qec]" to run it.

Run the checks

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

starter.py

Python
"""Starter: the bit-flip repetition code under code-capacity noise.

Data layout: a batch of errors is a (shots, n) array of 0/1 integers; entry
[s, j] = 1 means data qubit j suffered an X error in shot s. The syndrome bit
i (i = 0..n-2) is the parity of qubits i and i+1, i.e. the outcome of Z_i Z_{i+1}.
"""

from __future__ import annotations

import math

import numpy as np


def exact_logical_error_rate(n: int, p: float) -> float:
    """Exact logical error probability of the n-qubit code with minimum-weight decoding.

    Each qubit flips independently with probability p (code-capacity noise, perfect
    syndrome measurement). Raise ValueError unless n is a positive odd integer and
    0 <= p <= 1.
    """
    raise NotImplementedError("exact_logical_error_rate: implement this function")


def syndromes(errors: np.ndarray) -> np.ndarray:
    """(shots, n) 0/1 errors -> (shots, n-1) 0/1 syndromes, bit i = e_i XOR e_{i+1}."""
    raise NotImplementedError("syndromes: implement this function")


def decode_min_weight(syn: np.ndarray, n: int) -> np.ndarray:
    """Minimum-weight correction for each syndrome row.

    Input: (shots, n-1) syndromes. Output: (shots, n) 0/1 corrections c with
    syndromes(c) == syn and the smallest possible Hamming weight. For odd n the
    minimum is unique.
    """
    raise NotImplementedError("decode_min_weight: implement this function")


def logical_failures(errors: np.ndarray, corrections: np.ndarray) -> np.ndarray:
    """Boolean per shot: True when error XOR correction is the logical operator X...X.

    Raise ValueError if some residual is neither all zeros nor all ones (the
    correction did not reproduce the syndrome).
    """
    raise NotImplementedError("logical_failures: implement this function")


def sample_code_capacity(n: int, p: float, shots: int, seed: int) -> int:
    """Number of logical failures in `shots` seeded trials.

    Sampling is fixed so results are reproducible:
    rng = np.random.default_rng(seed); errors = rng.random((shots, n)) < p.
    Decode with decode_min_weight from the syndromes only.
    """
    raise NotImplementedError("sample_code_capacity: implement this function")


def exact_memory_failure(n: int, p: float, rounds: int) -> float:
    """Exact probability that the logical bit is flipped after `rounds` rounds.

    In each round every qubit flips with probability p, then a perfect syndrome
    measurement and minimum-weight correction follow. The logical bit ends flipped
    when an odd number of rounds failed: (1 - (1 - 2 p_L)^rounds) / 2.
    """
    raise NotImplementedError("exact_memory_failure: implement this function")


def sample_memory(n: int, p: float, rounds: int, shots: int, seed: int) -> int:
    """Monte Carlo of the multi-round memory above; returns the number of failures.

    rng = np.random.default_rng(seed); in round r draw rng.random((shots, n)) < p,
    add (XOR) the new flips to the current error, measure the syndrome perfectly,
    apply the minimum-weight correction. After the last round count the shots
    whose remaining error is X...X.
    """
    raise NotImplementedError("sample_memory: implement this function")

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 itertools
import math

import numpy as np
import pytest


def _within(observed_failures, shots, exact, sigmas=5.0):
    sigma = math.sqrt(exact * (1 - exact) / shots)
    return abs(observed_failures / shots - exact) <= sigmas * sigma + 1.0 / shots


@pytest.mark.parametrize("p", [0.0, 0.001, 0.05, 0.2, 0.5, 0.8, 1.0])
def test_three_qubit_closed_form(p):
    assert target.exact_logical_error_rate(3, p) == pytest.approx(3 * p**2 - 2 * p**3, abs=1e-12)


def test_one_qubit_is_unprotected_and_leading_order():
    assert target.exact_logical_error_rate(1, 0.123) == pytest.approx(0.123)
    # Leading order for small p: C(n, (n+1)/2) p^((n+1)/2).
    for n in (3, 5, 7, 9):
        t = (n + 1) // 2
        p = 1e-4
        assert target.exact_logical_error_rate(n, p) / (math.comb(n, t) * p**t) == pytest.approx(1.0, rel=1e-2)


def test_invalid_inputs():
    with pytest.raises(ValueError):
        target.exact_logical_error_rate(4, 0.1)
    with pytest.raises(ValueError):
        target.exact_logical_error_rate(3, 1.5)


def test_syndromes_shape_and_values():
    errors = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 1]], dtype=np.uint8)
    expected = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]])
    assert np.array_equal(target.syndromes(errors), expected)


@pytest.mark.parametrize("n", [3, 5, 7])
def test_decoder_corrects_every_error_of_weight_up_to_t(n):
    t = (n - 1) // 2
    errors = []
    for w in range(t + 1):
        for support in itertools.combinations(range(n), w):
            e = np.zeros(n, dtype=np.uint8)
            e[list(support)] = 1
            errors.append(e)
    errors = np.array(errors)
    corrections = target.decode_min_weight(target.syndromes(errors), n)
    assert np.array_equal(corrections, errors)
    assert not target.logical_failures(errors, corrections).any()


@pytest.mark.parametrize("n", [3, 5])
def test_decoder_is_consistent_and_minimal_on_all_errors(n):
    errors = np.array(list(itertools.product([0, 1], repeat=n)), dtype=np.uint8)
    syn = target.syndromes(errors)
    corrections = target.decode_min_weight(syn, n)
    assert np.array_equal(target.syndromes(corrections), syn)
    # Independent check by brute force: the only other error with this syndrome is the complement.
    assert np.all(corrections.sum(axis=1) <= (1 - corrections).sum(axis=1))
    failures = target.logical_failures(errors, corrections)
    assert np.array_equal(failures, errors.sum(axis=1) > n // 2)


def test_logical_failures_rejects_inconsistent_correction():
    with pytest.raises(ValueError):
        target.logical_failures(np.array([[1, 0, 0]]), np.array([[0, 1, 0]]))


@pytest.mark.parametrize("n,p", [(3, 0.1), (5, 0.1), (7, 0.2), (5, 0.6)])
def test_monte_carlo_matches_binomial_formula(n, p):
    shots = 100_000
    failures = target.sample_code_capacity(n, p, shots, seed=2026)
    assert _within(failures, shots, target.exact_logical_error_rate(n, p))


def test_monte_carlo_is_reproducible():
    a = target.sample_code_capacity(5, 0.1, 10_000, seed=99)
    b = target.sample_code_capacity(5, 0.1, 10_000, seed=99)
    assert a == b


def test_agrees_with_ketqat_repetition_code_product(tmp_path, monkeypatch):
    catalog = pytest.importorskip("ketqat_runner.catalog")
    monkeypatch.setenv("KETQAT_HOME", str(tmp_path))
    n, p, shots = 5, 0.1, 50_000
    record = catalog.run("[email protected]", seed=11, n=n, physical_error_rate=p, shots=shots)
    result = record.result
    assert target.exact_logical_error_rate(n, p) == pytest.approx(result["exact_logical_error_rate"], rel=1e-12)
    # Two independent Monte Carlo estimates (different samplers) must agree statistically.
    ours = target.sample_code_capacity(n, p, shots, seed=11) / shots
    theirs = result["logical_error_rate"]
    exact = result["exact_logical_error_rate"]
    sigma = math.sqrt(2 * exact * (1 - exact) / shots)
    assert abs(ours - theirs) < 5 * sigma


@pytest.mark.parametrize("n,p,rounds", [(3, 0.05, 1), (3, 0.05, 10), (5, 0.1, 20)])
def test_memory_matches_exact_formula(n, p, rounds):
    shots = 40_000
    failures = target.sample_memory(n, p, rounds, shots, seed=5)
    assert _within(failures, shots, target.exact_memory_failure(n, p, rounds))


def test_memory_exact_limits():
    assert target.exact_memory_failure(3, 0.05, 1) == pytest.approx(target.exact_logical_error_rate(3, 0.05))
    # Many rounds: the stored bit is randomised, the failure probability tends to 1/2.
    assert target.exact_memory_failure(3, 0.2, 2000) == pytest.approx(0.5, abs=1e-6)

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. Under code-capacity noise with p=0.02p = 0.02 (independent bit flips, perfect syndrome measurement, minimum-weight decoding), what is the exact logical error probability of the 5-qubit repetition code?

    1 pt
  2. For the 5-qubit bit-flip repetition code with checks Z0Z1,Z1Z2,Z2Z3,Z3Z4Z_0Z_1, Z_1Z_2, Z_2Z_3, Z_3Z_4, the syndrome is (1,0,0,1)(1, 0, 0, 1). Which correction does the minimum-weight decoder apply?

    1 pt
  3. Run your sample_code_capacity(5, 0.1, 100_000, seed=2026) from the exercise (sampling exactly as specified: rng = np.random.default_rng(2026), errors = rng.random((shots, n)) < p). How many logical failures does it report?

    2 pts

    Computed by running exercise “repetition-code-monte-carlo” on your computer.

  4. A 3-qubit bit-flip code is used as a memory for T=50T = 50 rounds. In each round every qubit flips with probability p=0.02p = 0.02, then the syndrome is measured perfectly and corrected. What is the probability that the stored bit is wrong at the end?

    1 pt
  5. Run your sample_memory(3, 0.05, 10, 100_000, seed=7) from the exercise. How many of the 100,000 shots end with the logical bit flipped?

    2 pts

    Computed by running exercise “repetition-code-monte-carlo” on your computer.

  6. Which pair of operators are the parity checks of the three-qubit phase-flip code with code words ∣+++⟩\ket{{+}{+}{+}} and ∣−−−⟩\ket{{-}{-}{-}}?

    1 pt
  7. Syndrome measurements now fail with some probability. Select every true statement.

    1 pt

    Select all that apply.

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

References

  1. Peter W. Shor (1995). Scheme for reducing decoherence in quantum computer memory. Physical Review A 52, R2493-R2496. doi:10.1103/PhysRevA.52.R2493
  2. Google Quantum AI (2023). Suppressing quantum errors by scaling a surface code logical qubit. Nature 614, 676-681. doi:10.1038/s41586-022-05434-1
  3. Michael A. Nielsen, Isaac L. Chuang (2010). Quantum Computation and Quantum Information (10th Anniversary Edition). Cambridge University Press. doi:10.1017/CBO9780511976667