Skip to main content
KetQat

Appearance

Lesson 445 min

Measurement and probability

The Born rule, measurement bases, the state-update rule, and estimating probabilities from shots.

After this lesson you can

  • Apply the Born rule to predict outcome probabilities in the computational basis and in any orthonormal basis
  • Implement a measurement in another basis as a basis change followed by a computational-basis measurement
  • Apply the state-update rule and explain why measurement is irreversible
  • Compute expectation values of observables from a state and from outcome counts
  • Estimate a probability from N shots and quantify its standard error sqrt(p(1-p)/N)

Read first: Quantum gates and unitary transformations

Where the numbers come from

A quantum computer never shows you its amplitudes. Every run of a circuit ends with a measurement that returns classical bits, and a different run of the same circuit may return different bits. Everything we learn about a state comes from the statistics of many such runs, called shots. This lesson makes three things precise: which probabilities quantum mechanics predicts, what happens to the state when it is measured, and how well a finite number of shots pins those probabilities down. The postulates follow Nielsen and Chuang, Section 2.2.

The Born rule

Let {∣b0⟩,…,∣bd−1⟩}\{\ket{b_0}, \dots, \ket{b_{d-1}}\} be an orthonormal basis of the state space. A projective measurement in this basis on the state ∣ψ⟩\ket\psi returns outcome kk with probability

Pr⁡[k]=∣⟨bk∣ψ⟩∣2.\Pr[k] = \abs{\braket{b_k}{\psi}}^2 .

These numbers are non-negative and sum to one, because expanding ∣ψ⟩=∑k⟨bk∣ψ⟩∣bk⟩\ket\psi = \sum_k \braket{b_k}{\psi}\ket{b_k} in an orthonormal basis gives ∑k∣⟨bk∣ψ⟩∣2=∥ψ∥2=1\sum_k \abs{\braket{b_k}{\psi}}^2 = \norm{\psi}^2 = 1. In the computational basis this is the rule from the first lesson: Pr⁡[k]=∣ψk∣2\Pr[k] = \abs{\psi_k}^2.

It is often convenient to write the measurement with projectors Pk=∣bk⟩⟨bk∣P_k = \ketbra{b_k}{b_k}. They satisfy Pk2=PkP_k^2 = P_k, PjPk=0P_jP_k = 0 for j≠kj\neq k and ∑kPk=I\sum_k P_k = I, and the Born rule reads Pr⁡[k]=⟨ψ∣Pk∣ψ⟩=∥Pk∣ψ⟩∥2\Pr[k] = \bra\psi P_k\ket\psi = \norm{P_k\ket\psi}^2. (Quantum mechanics also allows more general measurements, described by positive operators that need not be projectors. They are not needed in this course, and any of them can be realised as a projective measurement on a larger system.)

Measuring in another basis

Hardware typically measures only in the computational basis. To measure in a basis {∣bk⟩}\{\ket{b_k}\}, apply the unitary U†U^\dagger where UU is the matrix whose columns are the ∣bk⟩\ket{b_k}, and then measure in the computational basis. This works because U†∣bk⟩=∣k⟩U^\dagger\ket{b_k} = \ket k, so

∣⟨k∣U†∣ψ⟩∣2=∣⟨bk∣ψ⟩∣2.\abs{\bra k U^\dagger\ket\psi}^2 = \abs{\braket{b_k}{\psi}}^2 .

The two most common cases:

  • XX basis {∣+⟩,∣−⟩}\{\ket+, \ket-\}: the matrix with these columns is HH, and H†=HH^\dagger = H, so apply HH and measure. Outcome 0 means "+", outcome 1 means "−".
  • YY basis {∣+i⟩,∣−i⟩}\{\ket{+i}, \ket{-i}\}: the matrix with these columns is U=SH=12(11i−i)U = SH = \frac{1}{\sqrt2}\begin{pmatrix}1&1\\ i&-i\end{pmatrix}, so U†=HS†U^\dagger = HS^\dagger. Apply S†S^\dagger, then HH, then measure.
Quantum circuit on 2 wires (a, b). step 1: H on a; SDG on b. step 2: H on b. step 3: measure a; measure b.abHS†H
Measuring qubit a in the X basis and qubit b in the Y basis

On the Bloch sphere, each orthonormal basis is an axis, and measuring along an axis m⃗\vec m gives the "+" outcome with probability (1+r⃗⋅m⃗)/2(1 + \vec r\cdot\vec m)/2, by the overlap formula of the Bloch-sphere lesson. The basis-change gate simply rotates the chosen axis onto the zz axis.

What measurement does to the state

State-update rule. If outcome kk occurs, the state immediately afterwards is

∣ψ′⟩=Pk∣ψ⟩∥Pk∣ψ⟩∥.\ket{\psi'} = \frac{P_k\ket\psi}{\norm{P_k\ket\psi}} .

For a basis measurement this is ∣bk⟩\ket{b_k} up to a global phase. Three consequences matter in practice.

  1. Repeatability. Measuring ∣ψ′⟩\ket{\psi'} again in the same basis returns kk with certainty. A second measurement teaches you nothing new.
  2. Irreversibility. Different input states (for example ∣+⟩\ket+ and ∣0⟩\ket0) can both end up as ∣0⟩\ket0 after the outcome 0. No unitary can undo this, because a unitary never maps two different states to the same one. Measurement is the only non-unitary step in the circuits of this course so far.
  3. Disturbance. Measuring in one basis erases information about the others. Measure ∣+⟩\ket{+} in the computational basis, get outcome 0, and the state is now ∣0⟩\ket0; a subsequent XX-basis measurement gives "+" only half the time.

On multi-qubit states, measuring some qubits updates the others as well; the entanglement lesson uses this.

Expectation values

An observable is a Hermitian matrix O=∑kλkPkO = \sum_k \lambda_k P_k; measuring it means measuring in its eigenbasis and reporting the eigenvalue λk\lambda_k. Its average over many shots is the expectation value

⟨O⟩=∑kλkPr⁡[k]=∑kλk⟨ψ∣Pk∣ψ⟩=⟨ψ∣O∣ψ⟩.\expval O = \sum_k \lambda_k \Pr[k] = \sum_k \lambda_k \bra\psi P_k \ket\psi = \bra\psi O\ket\psi .

For ZZ, the eigenvalues are +1+1 for ∣0⟩\ket0 and −1-1 for ∣1⟩\ket1, so ⟨Z⟩=Pr⁡[0]−Pr⁡[1]\expval Z = \Pr[0] - \Pr[1]. For XX, measure in the XX basis and take the same difference. These are the Bloch-vector components of the previous lessons, and this is how they are measured in an experiment.

Worked example

Let ∣ψ⟩=cos⁡π8∣0⟩+sin⁡π8∣1⟩\ket\psi = \cos\frac\pi8\ket0 + \sin\frac\pi8\ket1, the Bloch-sphere state with θ=π/4\theta = \pi/4, φ=0\varphi = 0.

  1. Computational basis: Pr⁡[0]=cos⁡2π8=1+cos⁡(π/4)2≈0.854\Pr[0] = \cos^2\frac\pi8 = \frac{1+\cos(\pi/4)}{2} \approx 0.854.
  2. XX basis: ⟨+∣ψ⟩=(cos⁡π8+sin⁡π8)/2\braket{+}{\psi} = (\cos\frac\pi8 + \sin\frac\pi8)/\sqrt2, so Pr⁡[+]=1+2sin⁡π8cos⁡π82=1+sin⁡(π/4)2≈0.854\Pr[+] = \frac{1 + 2\sin\frac\pi8\cos\frac\pi8}{2} = \frac{1 + \sin(\pi/4)}{2} \approx 0.854. The two numbers agree because the Bloch vector (sin⁡π4,0,cos⁡π4)(\sin\frac\pi4, 0, \cos\frac\pi4) makes the same angle with the xx and zz axes.
  3. ⟨Z⟩=cos⁡π4≈0.707\expval Z = \cos\frac\pi4 \approx 0.707 and ⟨X⟩=sin⁡π4≈0.707\expval X = \sin\frac\pi4 \approx 0.707.
  4. Suppose the XX-basis measurement returned "+". The state is now ∣+⟩\ket+, and a computational-basis measurement would give 0 with probability 1/21/2, not 0.854.

From shots to estimates

A single shot of a two-outcome measurement is a Bernoulli trial: outcome 0 with probability pp. With NN independent shots, the number of zeros n0n_0 is binomially distributed, and the natural estimate is

p^=n0N,E[p^]=p,Var⁡(p^)=p(1−p)N.\hat p = \frac{n_0}{N}, \qquad \mathbb E[\hat p] = p, \qquad \operatorname{Var}(\hat p) = \frac{p(1-p)}{N}.

The standard error SE=p(1−p)/N\mathrm{SE} = \sqrt{p(1-p)/N} is the typical size of the statistical error. In practice pp is unknown and we plug in p^\hat p. For large NN the binomial distribution is close to a normal distribution, so p^±1.96 SE^\hat p \pm 1.96\,\widehat{\mathrm{SE}} is an approximate 95% confidence interval. This approximation is poor when NpNp or N(1−p)N(1-p) is small (for example when no zeros were seen at all); then use an interval designed for proportions, such as the Wilson score interval.

Two consequences shape every experiment:

  • Error shrinks like 1/N1/\sqrt N. Halving the error costs four times the shots. To reach SE=0.01\mathrm{SE} = 0.01 at p=0.5p = 0.5 you need N=p(1−p)/0.012=2500N = p(1-p)/0.01^2 = 2500 shots; for 0.0010.001, a quarter of a million.
  • Expectation values inherit shot noise. From counts, ⟨Z⟩^=(n0−n1)/N=2p^−1\widehat{\expval Z} = (n_0 - n_1)/N = 2\hat p - 1, whose standard error is 2 SE=(1−⟨Z⟩2)/N2\,\mathrm{SE} = \sqrt{(1-\expval Z^2)/N}.

Sampling the worked example in the XX basis with a fixed seed:

import numpy as np

theta = np.pi / 4
psi = np.array([np.cos(theta / 2), np.sin(theta / 2)])
H = np.array([[1, 1], [1, -1]]) / np.sqrt(2)

probs = np.abs(H @ psi) ** 2            # measuring in the X basis = apply H, then measure
shots = 1000
counts = np.random.default_rng(2026).multinomial(shots, probs)
p_hat = counts[0] / shots
se = np.sqrt(p_hat * (1 - p_hat) / shots)
x_hat = (counts[0] - counts[1]) / shots
print(np.round(probs, 4), counts)
print(f"p_hat = {p_hat:.3f} +/- {se:.3f},  <X> estimate = {x_hat:.3f} (exact {np.sin(theta):.3f})")

With NumPy 2.5 this prints counts [861 139], p^=0.861±0.011\hat p = 0.861 \pm 0.011 and ⟨X⟩^=0.722\widehat{\expval X} = 0.722 against the exact 0.7070.707. The estimate is off by about 0.0070.007 in p^\hat p, less than one standard error: exactly the size of deviation shot noise predicts. A different seed gives a different estimate; the exercise checks over 400 seeds that the ±2\pm 2 SE interval covers the true value about 95% of the time.

Common mistakes

  • Expecting amplitudes from one shot. A single shot returns one outcome. Probabilities, and through them ∣amplitudes∣\abs{\text{amplitudes}}, are learned only from many shots, and phases only by measuring in several bases.
  • Forgetting the basis change. "Measure in the XX basis" means apply HH first. Applying HH after a computational-basis measurement does nothing to the recorded bit.
  • Confusing UU and U†U^\dagger. To measure in the basis given by the columns of UU, apply U†U^\dagger; for the YY basis that is HS†HS^\dagger, i.e. S†S^\dagger first.
  • Reporting p^\hat p without its error. An estimate from 100 shots and one from 10610^6 shots differ in precision by a factor of 100.
  • Trusting the normal interval at the edges. With n0=0n_0 = 0 the plug-in standard error is 0, which does not mean p=0p = 0.

Summary

  • Born rule: Pr⁡[k]=∣⟨bk∣ψ⟩∣2=⟨ψ∣Pk∣ψ⟩\Pr[k] = \abs{\braket{b_k}{\psi}}^2 = \bra\psi P_k\ket\psi for a measurement in the basis {∣bk⟩}\{\ket{b_k}\}.
  • To measure in another basis, apply U†U^\dagger (columns of UU = basis) and measure in the computational basis.
  • After outcome kk the state becomes Pk∣ψ⟩/∥Pk∣ψ⟩∥P_k\ket\psi/\norm{P_k\ket\psi}; measurement is repeatable and irreversible.
  • ⟨O⟩=⟨ψ∣O∣ψ⟩\expval O = \bra\psi O\ket\psi; ⟨Z⟩=Pr⁡[0]−Pr⁡[1]\expval Z = \Pr[0]-\Pr[1].
  • From NN shots, p^=n0/N\hat p = n_0/N with standard error p(1−p)/N\sqrt{p(1-p)/N}.

The exercise implements measurement in arbitrary bases, the update rule and the estimate with its standard error. Next, Multiple qubits and entanglement moves from one qubit to several.

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.

Born rule, state update and shot noise

introductory · about 30 min · needs numpy

You will implement projective measurement in an arbitrary orthonormal basis, the state-update rule, expectation values, and the statistics of estimating a probability from a finite number of shots.

A basis is given as a unitary matrix basis whose columns are the basis vectors ∣b0⟩,∣b1⟩,…\ket{b_0}, \ket{b_1}, \dots For example numpy.eye(2) is the computational basis and H = [[1, 1], [1, -1]] / sqrt(2) has columns ∣+⟩\ket+ and ∣−⟩\ket-.

Functions to implement (in starter.py)

Function Contract
outcome_probabilities(psi, basis) Return the array (∣⟨bk∣ψ⟩∣2)k\big(\abs{\braket{b_k}{\psi}}^2\big)_k.
post_measurement_state(psi, basis, outcome) Return the normalised state Pk∣ψ⟩/∥Pk∣ψ⟩∥P_k\ket\psi/\norm{P_k\ket\psi} with Pk=∣bk⟩⟨bk∣P_k = \ketbra{b_k}{b_k}. Raise ValueError if the outcome has probability below 1e-12.
expectation_value(psi, observable) Return the real number ⟨ψ∣O∣ψ⟩\bra\psi O\ket\psi for a Hermitian matrix OO.
sample_counts(probabilities, shots, seed) Return an integer array of outcome counts. Use exactly rng = numpy.random.default_rng(seed) followed by rng.multinomial(shots, probabilities), so that your counts match the quiz.
estimate_probability(count, shots) Return (p_hat, standard_error) with p^=count/N\hat p = \text{count}/N and SE^=p^(1−p^)/N\widehat{\mathrm{SE}} = \sqrt{\hat p(1-\hat p)/N}.

What the checks verify

  • Probabilities in the computational, XX and YY bases match the analytic values from the lesson and sum to 1 in random bases.
  • Measuring the post-measurement state again in the same basis repeats the outcome with probability 1, and the update rule keeps the phase of ∣ψ⟩\ket\psi.
  • ⟨Z⟩=Pr⁡[0]−Pr⁡[1]\expval Z = \Pr[0] - \Pr[1] and ⟨X⟩\expval X equals the same difference in the {∣+⟩,∣−⟩}\{\ket+,\ket-\} basis (two independent routes to one number).
  • Counts sum to the number of shots and are reproducible for a fixed seed.
  • Over 400 seeded experiments with N=1000N = 1000 shots, the interval p^±2SE^\hat p \pm 2\widehat{\mathrm{SE}} contains the true probability in roughly 95% of them (the test accepts 90%–99%), and the spread of p^\hat p matches p(1−p)/N\sqrt{p(1-p)/N} within 15%.

Run the checks

python -m pip install numpy
python -m pytest test_exercise.py

The sampling checks rely on NumPy's default_rng (PCG64) stream. Counts for a given seed are stable within a NumPy version but NumPy does not promise identical streams across versions; the quiz values were produced with NumPy 2.5.

Terminal
python -m pip install numpy

starter.py

Python
"""Born rule, state update and shot noise (KetQat Commons, Foundations).

A basis is a unitary matrix whose COLUMNS are the basis vectors.
"""
import numpy as np


def outcome_probabilities(psi, basis):
    """Return the array of |<b_k|psi>|^2 for the columns b_k of basis."""
    raise NotImplementedError


def post_measurement_state(psi, basis, outcome):
    """Return P_k psi / ||P_k psi|| with P_k = |b_k><b_k|; ValueError if Pr[outcome] < 1e-12."""
    raise NotImplementedError


def expectation_value(psi, observable):
    """Return the real number <psi|O|psi> for a Hermitian matrix O."""
    raise NotImplementedError


def sample_counts(probabilities, shots, seed):
    """Return counts from rng = np.random.default_rng(seed); rng.multinomial(shots, probabilities)."""
    raise NotImplementedError


def estimate_probability(count, shots):
    """Return (p_hat, standard_error) with p_hat = count/shots and SE = sqrt(p_hat (1 - p_hat) / shots)."""
    raise NotImplementedError

test_exercise.py

Python
"""Checks for the born-rule-sampling exercise. Run: python -m pytest test_exercise.py"""
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 numpy as np
import pytest

S2 = np.sqrt(2)
COMPUTATIONAL = np.eye(2)
X_BASIS = np.array([[1, 1], [1, -1]]) / S2
Y_BASIS = np.array([[1, 1], [1j, -1j]]) / S2
X = np.array([[0, 1], [1, 0]])
Z = np.diag([1, -1])
RNG = np.random.default_rng(99)


def _bloch_state(theta, phi):
    return np.array([np.cos(theta / 2), np.exp(1j * phi) * np.sin(theta / 2)])


def _random_unitary(n):
    m = RNG.normal(size=(n, n)) + 1j * RNG.normal(size=(n, n))
    q, r = np.linalg.qr(m)
    return q * (np.diag(r) / abs(np.diag(r)))


def test_probabilities_match_bloch_formulas():
    for _ in range(30):
        theta, phi = RNG.uniform(0, np.pi), RNG.uniform(0, 2 * np.pi)
        psi = _bloch_state(theta, phi)
        r = [np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta)]
        # Pr[first basis vector] = (1 + r_axis) / 2 for the z, x and y axes
        assert np.allclose(target.outcome_probabilities(psi, COMPUTATIONAL), [(1 + r[2]) / 2, (1 - r[2]) / 2])
        assert np.allclose(target.outcome_probabilities(psi, X_BASIS), [(1 + r[0]) / 2, (1 - r[0]) / 2])
        assert np.allclose(target.outcome_probabilities(psi, Y_BASIS), [(1 + r[1]) / 2, (1 - r[1]) / 2])


def test_probabilities_sum_to_one_in_random_bases():
    for n in (2, 4, 8):
        psi = RNG.normal(size=n) + 1j * RNG.normal(size=n)
        psi /= np.linalg.norm(psi)
        p = target.outcome_probabilities(psi, _random_unitary(n))
        assert p.shape == (n,) and np.all(p >= 0) and np.isclose(p.sum(), 1)


def test_post_measurement_state_is_repeatable():
    for _ in range(20):
        psi = RNG.normal(size=2) + 1j * RNG.normal(size=2)
        psi /= np.linalg.norm(psi)
        U = _random_unitary(2)
        for k in (0, 1):
            after = target.post_measurement_state(psi, U, k)
            assert np.isclose(np.linalg.norm(after), 1)
            again = target.outcome_probabilities(after, U)
            assert np.isclose(again[k], 1.0)


def test_post_measurement_state_keeps_phase_and_rejects_impossible_outcomes():
    psi = np.array([1j, 1]) / S2
    after = target.post_measurement_state(psi, COMPUTATIONAL, 0)
    assert np.allclose(after, [1j, 0])
    with pytest.raises(ValueError):
        target.post_measurement_state(np.array([1, 0]), COMPUTATIONAL, 1)


def test_expectation_values_two_ways():
    for _ in range(20):
        psi = RNG.normal(size=2) + 1j * RNG.normal(size=2)
        psi /= np.linalg.norm(psi)
        pz = target.outcome_probabilities(psi, COMPUTATIONAL)
        px = target.outcome_probabilities(psi, X_BASIS)
        assert np.isclose(target.expectation_value(psi, Z), pz[0] - pz[1])
        assert np.isclose(target.expectation_value(psi, X), px[0] - px[1])


def test_sample_counts_are_reproducible_and_complete():
    a = target.sample_counts([0.2, 0.3, 0.5], 1000, seed=5)
    b = target.sample_counts([0.2, 0.3, 0.5], 1000, seed=5)
    assert np.array_equal(a, b) and a.sum() == 1000 and len(a) == 3
    assert np.array_equal(a, np.random.default_rng(5).multinomial(1000, [0.2, 0.3, 0.5]))


def test_estimate_probability_formula():
    p_hat, se = target.estimate_probability(300, 1000)
    assert np.isclose(p_hat, 0.3) and np.isclose(se, np.sqrt(0.3 * 0.7 / 1000))
    assert target.estimate_probability(0, 50) == (0.0, 0.0)


def test_two_standard_error_intervals_cover_about_95_percent():
    p, shots = 0.3, 1000
    hits, estimates = 0, []
    for seed in range(400):
        n0 = target.sample_counts([p, 1 - p], shots, seed)[0]
        p_hat, se = target.estimate_probability(n0, shots)
        estimates.append(p_hat)
        hits += abs(p_hat - p) <= 2 * se
    assert 0.90 <= hits / 400 <= 0.99
    assert abs(np.std(estimates) / np.sqrt(p * (1 - p) / shots) - 1) < 0.15

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. The state ∣ψ⟩=32∣0⟩+12∣1⟩\ket\psi = \frac{\sqrt3}{2}\ket0 + \frac12\ket1 is measured in the {∣+⟩,∣−⟩}\{\ket+,\ket-\} basis. What is the probability of the outcome "−"?

    1 pt
  2. Hardware measures only in the computational basis. Which gate sequence, applied before that measurement, implements a measurement in the {∣+i⟩,∣−i⟩}\{\ket{+i}, \ket{-i}\} basis (outcome 0 meaning ∣+i⟩\ket{+i})?

    1 pt
  3. The state ∣+⟩\ket+ is measured in the computational basis and the outcome is 0. The qubit is then measured in the {∣+⟩,∣−⟩}\{\ket+,\ket-\} basis. What is the probability of "+" in this second measurement?

    1 pt
  4. Let psi = numpy.array([numpy.cos(numpy.pi/8), numpy.sin(numpy.pi/8)]). With your exercise functions compute probs = outcome_probabilities(psi, numpy.eye(2)), then counts = sample_counts(probs, 1000, seed=7), then estimate_probability(counts[0], 1000). Enter p^\hat p.

    1 pt

    Computed by running exercise “born-rule-sampling” on your computer.

  5. You expect p≈0.5p \approx 0.5. How many shots NN are needed so that the standard error p(1−p)/N\sqrt{p(1-p)/N} equals 0.0050.005?

    1 pt
  6. In 1000 computational-basis shots you observe outcome 0 exactly 620 times. What is the estimate of ⟨Z⟩\expval Z?

    1 pt
  7. 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. Michael A. Nielsen, Isaac L. Chuang (2010). Quantum Computation and Quantum Information (10th Anniversary Edition). Cambridge University Press. doi:10.1017/CBO9780511976667