38 min read

A classical bit is the simplest possible information-bearing system. It can be in one of two states, conventionally labeled 0 and 1. Physically, a bit might be a voltage level in a transistor (0V for 0, 5V for 1), a magnetic domain on a hard drive...

Chapter 2: The Qubit: Superposition, the Bloch Sphere, and Why a Quantum Bit Is Fundamentally Different from a Classical Bit

Learning Objectives

By the end of this chapter, you will be able to:

  • Define a qubit mathematically as a vector in $\mathbb{C}^2$.
  • Explain superposition in terms of probability amplitudes and the Born rule.
  • Visualize single-qubit states on the Bloch sphere.
  • Distinguish between the mathematical state and the measurement outcome.
  • Write Qiskit code to create, manipulate, and measure a single qubit.
  • Understand why complex numbers are essential to quantum state representation.
  • Derive the Bloch sphere parametrization from the normalization condition and global phase equivalence.
  • Compute measurement probabilities in arbitrary bases.
  • Distinguish pure states from mixed states using the density matrix formalism.
  • Recognize the physical implementations of qubits and their engineering challenges.

2.1 The Classical Bit: A Binary World

A classical bit is the simplest possible information-bearing system. It can be in one of two states, conventionally labeled 0 and 1. Physically, a bit might be a voltage level in a transistor (0V for 0, 5V for 1), a magnetic domain on a hard drive, or a pit on an optical disc. The key property is determinism: at any moment, the bit is definitively 0 or definitively 1. Reading the bit tells you which state it was in, and reading it again gives the same answer.

A system of $n$ classical bits can represent exactly one $n$-bit string at a time. To represent all $2^n$ possible strings, you would need $2^n$ separate $n$-bit registers. The state space grows linearly with the number of bits: $n$ bits give you an $n$-dimensional state space (each bit is one dimension).

2.1.1 Information Content of a Classical Bit

A single classical bit carries exactly one bit (the unit of information) of information. Claude Shannon formalized this in 1948: the information content of a random variable $X$ that takes values 0 and 1 with equal probability is:

$$H(X) = -\sum_x p(x) \log_2 p(x) = -\frac{1}{2}\log_2\frac{1}{2} - \frac{1}{2}\log_2\frac{1}{2} = 1 \text{ bit}$$

If the bit is biased (e.g., 0 with probability 0.9, 1 with probability 0.1), its information content is less:

$$H(X) = -0.9\log_2 0.9 - 0.1\log_2 0.1 \approx 0.469 \text{ bits}$$

This will be important later when we compare classical and quantum information content.

2.1.2 Operations on Classical Bits

Classical bits are manipulated by Boolean logic gates:

Gate Input Output Reversible?
AND (a, b) a ∧ b No (2 bits → 1 bit)
OR (a, b) a ∨ b No
NOT a ¬a Yes
XOR (a, b) a ⊕ b Yes (with one input preserved)
NAND (a, b) ¬(a ∧ b) No
Toffoli (a, b, c) (a, b, c ⊕ (a ∧ b)) Yes

Most classical gates are irreversible: they erase information. AND maps (0,0), (0,1), and (1,0) all to 0, so you cannot recover the inputs from the output. This irreversibility has physical consequences: Landauer's principle states that erasing one bit of information necessarily dissipates $k_B T \ln 2$ of energy, where $k_B$ is Boltzmann's constant and $T$ is the temperature.

In contrast, quantum gates are always reversible (unitary). This is not just a mathematical curiosity—it has deep physical implications related to the connection between information and thermodynamics.

Common Misconception: "A qubit is like a classical bit that can be 0, 1, or both at the same time." This is misleading. A qubit is a unit vector in a two-dimensional complex Hilbert space. The phrase "both at the same time" obscures the precise mathematical structure. A qubit in superposition $\alpha|0\rangle + \beta|1\rangle$ is not "0 and 1 simultaneously"—it is a definite state in the vector space that happens to have nonzero components along both basis directions.


2.2 The Qubit: A Vector in $\mathbb{C}^2$

A qubit is a two-level quantum system. Mathematically, the state of a qubit is a unit vector in a two-dimensional complex Hilbert space $\mathbb{C}^2$. We write this state in Dirac notation (or bra-ket notation) as a ket:

$$|\psi\rangle = \alpha|0\rangle + \beta|1\rangle$$

where:

  • $|0\rangle$ and $|1\rangle$ are orthonormal basis vectors spanning the state space.
  • $\alpha, \beta \in \mathbb{C}$ are complex numbers called probability amplitudes.
  • The normalization condition $|\alpha|^2 + |\beta|^2 = 1$ must hold.

In vector form, using the standard computational basis:

$$|0\rangle = \begin{pmatrix} 1 \\ 0 \end{pmatrix}, \quad |1\rangle = \begin{pmatrix} 0 \\ 1 \end{pmatrix}, \quad |\psi\rangle = \begin{pmatrix} \alpha \\ \beta \end{pmatrix}$$

The normalization condition is simply the requirement that $|\psi\rangle$ is a unit vector:

$$\langle\psi|\psi\rangle = |\alpha|^2 + |\beta|^2 = 1$$

Recurring Theme: Quantum computing is linear algebra, not magic. A qubit is a vector. A quantum gate is a matrix. Measurement is a projection. If you understand these three sentences, you understand the mathematical core of quantum computing.

2.2.1 Why Complex Numbers?

You might wonder: why are $\alpha$ and $\beta$ complex, rather than real? This is not an arbitrary choice—it is forced upon us by nature. There are three compelling reasons:

Reason 1: Physical necessity. Experiments (starting with the Stern-Gerlach experiment in 1922) demonstrate that quantum states require complex amplitudes to correctly predict interference patterns. The relative phase between paths in an interference experiment can be any angle, not just 0 or $\pi$.

Reason 2: Mathematical structure. The set of valid single-qubit states with real amplitudes forms a semicircle ($\theta \in [0, \pi]$ with $\phi = 0$), while complex amplitudes give the full Bloch sphere. Without complex amplitudes, we lose half the state space and cannot represent states like $|+i\rangle = \frac{1}{\sqrt{2}}(|0\rangle + i|1\rangle)$, which are essential for quantum computation.

Reason 3: The Schrödinger equation. The time evolution of a quantum state is governed by the Schrödinger equation:

$$i\hbar\frac{d}{dt}|\psi(t)\rangle = \hat{H}|\psi(t)\rangle$$

The factor of $i$ on the left side means that even if the Hamiltonian $\hat{H}$ is real, the time evolution naturally generates complex phases. Starting from a real-amplitude state, time evolution will generally produce complex amplitudes.

Try It Yourself: Consider a qubit with real amplitudes: $|\psi\rangle = \cos\theta|0\rangle + \sin\theta|1\rangle$. Under time evolution with Hamiltonian $H = E|1\rangle\langle 1|$ (an energy gap $E$ for state $|1\rangle$), the state becomes $|\psi(t)\rangle = \cos\theta|0\rangle + e^{-iEt/\hbar}\sin\theta|1\rangle$. Even starting with real coefficients, time evolution generates complex phases. This is unavoidable.

2.2.2 Global Phase Is Physically Irrelevant

Two states that differ only by a global phase represent the same physical state:

$$|\psi\rangle \sim e^{i\gamma}|\psi\rangle$$

This is because measurement probabilities depend on $|\alpha|^2$ and $|\beta|^2$, which are invariant under global phase rotation. A global phase $e^{i\gamma}$ cancels out:

$$|\langle\phi|e^{i\gamma}\psi\rangle|^2 = |e^{i\gamma}|^2|\langle\phi|\psi\rangle|^2 = |\langle\phi|\psi\rangle|^2$$

This means that the space of physically distinct single-qubit states is not $\mathbb{C}^2$ (with normalization) but rather the complex projective line $\mathbb{C}P^1$, which is isomorphic to the 2-sphere $S^2$—the Bloch sphere.

Worked Example: The states $|+\rangle = \frac{1}{\sqrt{2}}(|0\rangle + |1\rangle)$ and $-|+\rangle = \frac{1}{\sqrt{2}}(-|0\rangle - |1\rangle)$ are physically identical. They produce the same measurement statistics in every possible experiment.

Important: Relative phase IS physically significant. The states $|+\rangle = \frac{1}{\sqrt{2}}(|0\rangle + |1\rangle)$ and $|-\rangle = \frac{1}{\sqrt{2}}(|0\rangle - |1\rangle)$ differ only in the relative phase between the $|0\rangle$ and $|1\rangle$ components, but they are maximally distinguishable: $|\langle+|-\rangle|^2 = 0$.


2.3 Superposition: The Heart of Quantum Weirdness

2.3.1 What Superposition Is

Superposition means that a qubit can exist in a linear combination of the basis states $|0\rangle$ and $|1\rangle$ simultaneously. This is not a statement about our ignorance—the qubit is not "really" 0 or 1 and we just don't know which. The qubit genuinely occupies both states at once, with the complex amplitudes $\alpha$ and $\beta$ encoding the "degree" to which it is in each basis state.

Consider the equal superposition state:

$$|+\rangle = \frac{1}{\sqrt{2}}|0\rangle + \frac{1}{\sqrt{2}}|1\rangle = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 \\ 1 \end{pmatrix}$$

This qubit is equally "0-ish" and "1-ish." But when we measure it, we never see "half-0 and half-1." We see either 0 or 1, each with probability $|1/\sqrt{2}|^2 = 1/2$.

2.3.2 The Born Rule

The Born rule connects the mathematical formalism to experimental outcomes: when a qubit in state $|\psi\rangle = \alpha|0\rangle + \beta|1\rangle$ is measured in the computational basis $\{|0\rangle, |1\rangle\}$, the probability of obtaining outcome 0 is $|\alpha|^2$, and the probability of obtaining outcome 1 is $|\beta|^2$.

After measurement, the qubit collapses into the state corresponding to the observed outcome. If we measure 0, the post-measurement state is $|0\rangle$. If we measure 1, it is $|1\rangle$. All information about $\alpha$ and $\beta$ (except their magnitudes) is destroyed.

This is the central tension of quantum computing: the state space is a continuous infinity of possibilities (any point on the Bloch sphere), but measurement extracts only a single classical bit. The art of quantum algorithm design is arranging interference so that the "interesting" information survives measurement.

Derivation of the Born Rule from the Measurement Postulate:

The measurement postulate of quantum mechanics states that measuring an observable $\hat{A}$ with spectral decomposition $\hat{A} = \sum_i \lambda_i |i\rangle\langle i|$ yields outcome $\lambda_i$ with probability:

$$p(\lambda_i) = |\langle i|\psi\rangle|^2$$

For measurement in the computational basis, the observable is $\hat{Z} = |0\rangle\langle 0| - |1\rangle\langle 1|$. The eigenvalues are $\lambda_0 = 1$ (for $|0\rangle$) and $\lambda_1 = -1$ (for $|1\rangle$). The probability of outcome $\lambda_0$ is:

$$p(0) = |\langle 0|\psi\rangle|^2 = |\alpha|^2$$

And the probability of outcome $\lambda_1$ is:

$$p(1) = |\langle 1|\psi\rangle|^2 = |\beta|^2$$

These probabilities sum to 1 by the normalization condition:

$$|\alpha|^2 + |\beta|^2 = 1$$

Worked Example: Consider the state $|\psi\rangle = \frac{1}{2}|0\rangle + \frac{\sqrt{3}}{2}|1\rangle$.

  • $p(0) = |1/2|^2 = 1/4$
  • $p(1) = |\sqrt{3}/2|^2 = 3/4$
  • Normalization check: $1/4 + 3/4 = 1$ ✓
  • After measuring 0: state collapses to $|0\rangle$
  • After measuring 1: state collapses to $|1\rangle$

Worked Example: Consider the state $|\psi\rangle = \frac{1+i}{2}|0\rangle + \frac{1-i}{2}|1\rangle$.

  • $p(0) = |(1+i)/2|^2 = \frac{(1+i)(1-i)}{4} = \frac{1+1}{4} = 1/2$
  • $p(1) = |(1-i)/2|^2 = \frac{(1-i)(1+i)}{4} = \frac{1+1}{4} = 1/2$
  • Normalization check: $1/2 + 1/2 = 1$ ✓

Note how the complex phase ($i$ and $-i$) has no effect on the measurement probabilities—it cancels out in $|\alpha|^2 = \alpha\alpha^*$. But the phase IS important for interference effects when this state evolves under a quantum gate.

2.3.3 What Superposition Is Not

Superposition is not:

  • A classical probability distribution. Classical probabilities are non-negative real numbers that sum to 1. Quantum amplitudes are complex numbers whose squared magnitudes sum to 1. The complex phases enable interference, which has no classical analogue.

  • Parallel computation in the classical sense. Having a superposition of $2^n$ states does not mean we can check all $2^n$ solutions simultaneously and pick the best one. Measurement only gives one answer. Quantum algorithms work by arranging interference, not by parallel brute force.

  • A statement about "multiple universes." The many-worlds interpretation is one philosophical stance; the mathematics works regardless of interpretation. The mathematical formalism makes testable predictions regardless of which interpretation you prefer.

Common Misconception: "A qubit in superposition is like a coin that's spinning—it's both heads and tails until you look at it." This analogy is misleading. A spinning coin is in a definite state at every instant (it just has angular momentum). A qubit in superposition is genuinely not in state $|0\rangle$ or $|1\rangle$—it is in a different kind of state that has no classical analogue. The correct analogy is: a qubit is like a vector pointing in an arbitrary direction on the Bloch sphere, and measurement projects it onto one of the two poles.

2.3.4 Superposition and Interference: A Worked Example

Let us see how superposition and interference combine to produce quantum effects. Consider a qubit starting in $|0\rangle$. We apply a Hadamard gate, then a Z gate, then another Hadamard:

Step 1: $|0\rangle \xrightarrow{H} \frac{1}{\sqrt{2}}|0\rangle + \frac{1}{\sqrt{2}}|1\rangle = |+\rangle$

Step 2: $|+\rangle \xrightarrow{Z} \frac{1}{\sqrt{2}}|0\rangle + \frac{1}{\sqrt{2}}(-|1\rangle) = \frac{1}{\sqrt{2}}|0\rangle - \frac{1}{\sqrt{2}}|1\rangle = |-\rangle$

Step 3: $|-\rangle \xrightarrow{H} H|-\rangle = \frac{1}{\sqrt{2}}(H|0\rangle - H|1\rangle) = \frac{1}{\sqrt{2}}(|+\rangle - |-\rangle) = \frac{1}{\sqrt{2}}\left(\frac{|0\rangle + |1\rangle}{\sqrt{2}} - \frac{|0\rangle - |1\rangle}{\sqrt{2}}\right) = |1\rangle$

So $HZH|0\rangle = |1\rangle$. The sequence $HZH$ acts as the X gate! We can verify this algebraically: $HZH = X$.

Let us verify this with matrices:

$$H = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix}, \quad Z = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}$$

$$HZ = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix}\begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix} = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & -1 \\ 1 & 1 \end{pmatrix}$$

$$HZH = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & -1 \\ 1 & 1 \end{pmatrix} \cdot \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix} = \frac{1}{2}\begin{pmatrix} 1-1 & 1+1 \\ 1+1 & 1-1 \end{pmatrix} = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} = X$$

This works because the Z gate flips the relative phase, and the second Hadamard converts this phase difference into a bit flip through interference. This is the same principle that powers all quantum algorithms.


2.4 The Bloch Sphere: A Geometric Picture

The Bloch sphere provides a powerful geometric visualization of a single qubit's state. Since $|\alpha|^2 + |\beta|^2 = 1$ and global phase is physically irrelevant, we can parameterize any single-qubit state (up to global phase) as:

$$|\psi\rangle = \cos\frac{\theta}{2}|0\rangle + e^{i\phi}\sin\frac{\theta}{2}|1\rangle$$

where $\theta \in [0, \pi]$ and $\phi \in [0, 2\pi)$.

2.4.1 Derivation of the Bloch Sphere Parametrization

Starting from the general state $|\psi\rangle = \alpha|0\rangle + \beta|1\rangle$ with $|\alpha|^2 + |\beta|^2 = 1$:

Step 1: Write $\alpha$ in polar form: $\alpha = r_1 e^{i\gamma_1}$ where $r_1 = |\alpha|$ and $\gamma_1 = \arg(\alpha)$.

Step 2: Write $\beta$ in polar form: $\beta = r_2 e^{i\gamma_2}$ where $r_2 = |\beta|$ and $\gamma_2 = \arg(\beta)$.

Step 3: Factor out the global phase: $|\psi\rangle = e^{i\gamma_1}(r_1|0\rangle + e^{i(\gamma_2 - \gamma_1)}r_2|1\rangle)$. Since global phase is irrelevant, we can write $|\psi\rangle \sim r_1|0\rangle + e^{i\phi}r_2|1\rangle$ where $\phi = \gamma_2 - \gamma_1$.

Step 4: Use normalization: $r_1^2 + r_2^2 = 1$. Set $r_1 = \cos(\theta/2)$ and $r_2 = \sin(\theta/2)$ for some $\theta \in [0, \pi]$. This is valid because $\cos^2(\theta/2) + \sin^2(\theta/2) = 1$.

Result: $|\psi\rangle \sim \cos(\theta/2)|0\rangle + e^{i\phi}\sin(\theta/2)|1\rangle$ with two real parameters $(\theta, \phi)$.

These two angles correspond to spherical coordinates on a unit sphere:

                    |0⟩ (north pole, θ=0)
                     *
                   / | \
                  /  |  \
                 /   |   \     θ = polar angle (0 to π)
                /    |    \    φ = azimuthal angle (0 to 2π)
               /     |     \   x = sin(θ)cos(φ)
              /      |      \  y = sin(θ)sin(φ)
             /       |       \ z = cos(θ)
            /        |        \
           /         |         \
          *----------+----------*-----> y-axis (x-z plane shown)
         /           |          / 
        /            |         /
       /             |        /
      /              |       /
     /               |      /
    /                |     /
   /                 |    /
  /                  |   /
 *-------------------+--/---------> x-axis
                     |
                     |
                     * |1⟩ (south pole, θ=π)

Key points on the Bloch sphere:

State $\theta$ $\phi$ Description
$|0\rangle$ 0 any North pole
$|1\rangle$ $\pi$ any South pole
$|+\rangle = \frac{|0\rangle + |1\rangle}{\sqrt{2}}$ $\pi/2$ 0 Positive x-axis
$|-\rangle = \frac{|0\rangle - |1\rangle}{\sqrt{2}}$ $\pi/2$ $\pi$ Negative x-axis
$|+i\rangle = \frac{|0\rangle + i|1\rangle}{\sqrt{2}}$ $\pi/2$ $\pi/2$ Positive y-axis
$|-i\rangle = \frac{|0\rangle - i|1\rangle}{\sqrt{2}}$ $\pi/2$ $3\pi/2$ Negative y-axis

2.4.2 The Bloch Vector

Every single-qubit state corresponds to a point on the surface of the Bloch sphere, described by the Bloch vector:

$$\vec{r} = (\sin\theta\cos\phi,\, \sin\theta\sin\phi,\, \cos\theta)$$

For a general state $|\psi\rangle = \alpha|0\rangle + \beta|1\rangle$, the Bloch vector can be computed as:

$$r_x = 2\text{Re}(\alpha^*\beta), \quad r_y = 2\text{Im}(\alpha^*\beta), \quad r_z = |\alpha|^2 - |\beta|^2$$

Verification for common states:

  • $|0\rangle$: $\alpha = 1, \beta = 0 \Rightarrow \vec{r} = (0, 0, 1)$ → north pole ✓
  • $|1\rangle$: $\alpha = 0, \beta = 1 \Rightarrow \vec{r} = (0, 0, -1)$ → south pole ✓
  • $|+\rangle$: $\alpha = \beta = 1/\sqrt{2} \Rightarrow r_x = 2\text{Re}(1/2) = 1, r_y = 0, r_z = 0$ → positive x ✓
  • $|+i\rangle$: $\alpha = 1/\sqrt{2}, \beta = i/\sqrt{2} \Rightarrow r_x = 2\text{Re}(-i/2) = 0, r_y = 2\text{Im}(-i/2) = 1, r_z = 0$ → positive y ✓

Worked Example: Find the Bloch vector for $|\psi\rangle = \frac{1}{2}|0\rangle + \frac{\sqrt{3}}{2}|1\rangle$.

$\alpha = 1/2, \beta = \sqrt{3}/2$

$r_x = 2\text{Re}(\alpha^*\beta) = 2\text{Re}\left(\frac{1}{2} \cdot \frac{\sqrt{3}}{2}\right) = \frac{\sqrt{3}}{2}$

$r_y = 2\text{Im}(\alpha^*\beta) = 2\text{Im}\left(\frac{1}{2} \cdot \frac{\sqrt{3}}{2}\right) = 0$

$r_z = |\alpha|^2 - |\beta|^2 = \frac{1}{4} - \frac{3}{4} = -\frac{1}{2}$

$\vec{r} = \left(\frac{\sqrt{3}}{2}, 0, -\frac{1}{2}\right)$, and $|\vec{r}| = \sqrt{3/4 + 0 + 1/4} = 1$ ✓ (unit vector)

The Bloch sphere makes single-qubit operations intuitive: every single-qubit unitary gate corresponds to a rotation of the Bloch sphere about some axis. The Pauli gates $X$, $Y$, $Z$ are rotations by $\pi$ about the $x$, $y$, and $z$ axes, respectively. The Hadamard gate $H$ is a rotation that maps the $z$-axis to the $x$-axis.

2.4.3 Mixed States and the Interior of the Bloch Sphere

Pure states live on the surface of the Bloch sphere ($|\vec{r}| = 1$). Mixed states—classical probabilistic mixtures of quantum states—live inside the sphere. A mixed state has Bloch vector with $|\vec{r}| < 1$.

The maximally mixed state $\rho = I/2$ has Bloch vector $\vec{r} = (0, 0, 0)$—it sits at the center of the sphere. This state represents complete ignorance: measuring in any basis gives 50/50 outcomes.

  Bloch sphere cross-section:

           |0⟩ (surface, pure state)
            *
           /|\
          / | \
         /  |  \
        /   |   \     Surface: pure states (|r|=1)
       /    |    \    Interior: mixed states (|r|<1)
      /     |     \   Center: maximally mixed (r=0)
     /      |      \
    /       |    *   \   ← mixed state (|r|=0.5)
   /        |   / \   \
  /         |  /   \   \
 *----------+-+-----+---*-----> equator
  \         |  \   /   /
   \        |   \ /   /
    \       |    *    /   ← another mixed state
     \      |      /
      \     |     /
       \    |    /
        \   |   /
         \  |  /
          \ | /
            *
           |1⟩ (surface, pure state)

2.5 Complex Numbers in Quantum States

Why complex numbers? Why not just real amplitudes?

The answer is interference. Real amplitudes can only produce constructive or destructive interference with phases of 0 or $\pi$ (sign flips). Complex amplitudes allow arbitrary phase relationships, enabling the rich interference patterns that quantum algorithms exploit.

Consider two paths to the same outcome with amplitudes $\alpha_1 = 1/2$ and $\alpha_2 = -1/2$. The total amplitude is $1/2 + (-1/2) = 0$—destructive interference, zero probability. With complex amplitudes, we can have $\alpha_1 = 1/2$ and $\alpha_2 = i/2$, giving total amplitude $(1+i)/2$ and probability $|(1+i)/2|^2 = 1/2$. The phase difference of $\pi/2$ (multiplication by $i$) changes the interference from fully destructive to partially constructive.

This is why quantum computing is fundamentally about managing complex amplitudes to make "good" paths interfere constructively and "bad" paths interfere destructively.

2.5.1 Interference Patterns: A Detailed Example

Let us trace through a quantum computation that demonstrates all three types of interference:

Constructive interference: Amplitudes add. If two paths lead to the same outcome with amplitudes $a$ and $a$, the total amplitude is $2a$ and the probability is $4a^2$—four times what either path would give alone.

Destructive interference: Amplitudes cancel. If two paths lead to the same outcome with amplitudes $a$ and $-a$, the total amplitude is 0 and the probability is 0—the outcome never occurs.

Partial interference: Amplitudes partially add or partially cancel. This happens when the amplitudes have a relative phase that is neither 0 nor $\pi$.

Worked Example: Consider a two-qubit system where we apply a Hadamard gate to each qubit and then perform a phase flip on one of the four basis states:

Starting state: $|00\rangle$

After $H \otimes H$:

$$|00\rangle \xrightarrow{H \otimes H} \frac{1}{2}(|00\rangle + |01\rangle + |10\rangle + |11\rangle)$$

Now apply a phase flip ($Z$ on the first qubit):

$$\frac{1}{2}(|00\rangle + |01\rangle - |10\rangle - |11\rangle)$$

Now apply $H \otimes H$ again:

$$\frac{1}{2}\left(\frac{1}{2}(|00\rangle + |01\rangle + |10\rangle + |11\rangle) + \frac{1}{2}(|00\rangle - |01\rangle + |10\rangle - |11\rangle) - \frac{1}{2}(|00\rangle + |01\rangle - |10\rangle - |11\rangle) - \frac{1}{2}(|00\rangle - |01\rangle - |10\rangle + |11\rangle)\right)$$

Collecting terms:

  • $|00\rangle$: $\frac{1}{4}(1 + 1 - 1 - 1) = 0$ → destructive interference
  • $|01\rangle$: $\frac{1}{4}(1 - 1 + 1 - (-1)) = \frac{1}{4}(1 - 1 + 1 + 1) = \frac{1}{2}$ → partial constructive interference
  • $|10\rangle$: $\frac{1}{4}(1 + 1 + (-1) + (-1)) = 0$ → destructive interference
  • $|11\rangle$: $\frac{1}{4}(1 + (-1) + (-1) + 1) = 0$ → destructive interference

Wait, this is getting complicated. Let me just verify: $(H \otimes H)(Z \otimes I)(H \otimes H)|00\rangle$. This simplifies to... let's compute it using matrices.

Actually, we know that $HZH = X$, so $(H \otimes H)(Z \otimes I)(H \otimes H) = (HZH) \otimes (HIH) = X \otimes I$. Therefore the result is $(X \otimes I)|00\rangle = |10\rangle$. The amplitude of $|00\rangle$, $|01\rangle$, and $|11\rangle$ are all zero due to destructive interference, while $|10\rangle$ has amplitude 1 due to constructive interference. This is a perfect example of how quantum algorithms work: all the "wrong" answers interfere destructively, and the "right" answer interferes constructively.


2.6 Measuring a Qubit

2.6.1 Measurement in the Computational Basis

Measurement in the computational basis $\{|0\rangle, |1\rangle\}$ is described by the projection operators:

$$M_0 = |0\rangle\langle 0| = \begin{pmatrix} 1 & 0 \\ 0 & 0 \end{pmatrix}, \quad M_1 = |1\rangle\langle 1| = \begin{pmatrix} 0 & 0 \\ 0 & 1 \end{pmatrix}$$

For a state $|\psi\rangle = \alpha|0\rangle + \beta|1\rangle$:

  • Probability of outcome 0: $p(0) = \langle\psi|M_0|\psi\rangle = |\alpha|^2$
  • Probability of outcome 1: $p(1) = \langle\psi|M_1|\psi\rangle = |\beta|^2$
  • Post-measurement state if outcome 0: $\frac{M_0|\psi\rangle}{\sqrt{p(0)}} = \frac{\alpha}{|\alpha|}|0\rangle$
  • Post-measurement state if outcome 1: $\frac{M_1|\psi\rangle}{\sqrt{p(1)}} = \frac{\beta}{|\beta|}|1\rangle$

Note that the post-measurement state picks up the phase of the original amplitude. For outcome 0, the state is $e^{i\arg(\alpha)}|0\rangle$, which is physically equivalent to $|0\rangle$ (global phase is irrelevant).

2.6.2 Measurement in Other Bases

We can measure in any orthonormal basis. The Hadamard basis (or $X$-basis) is:

$$|+\rangle = \frac{|0\rangle + |1\rangle}{\sqrt{2}}, \quad |-\rangle = \frac{|0\rangle - |1\rangle}{\sqrt{2}}$$

Measuring in this basis answers the question: "Is the qubit in $|+\rangle$ or $|-\rangle$?" A qubit in state $|0\rangle$ measured in the Hadamard basis yields $|+\rangle$ or $|-\rangle$ with equal probability $1/2$, because:

$$|0\rangle = \frac{1}{\sqrt{2}}|+\rangle + \frac{1}{\sqrt{2}}|-\rangle$$

The probability of getting $|+\rangle$ when measuring $|0\rangle$ in the Hadamard basis is:

$$p(+) = |\langle+|0\rangle|^2 = \left|\frac{1}{\sqrt{2}}\right|^2 = \frac{1}{2}$$

Worked Example: A qubit is in state $|\psi\rangle = \frac{3}{5}|0\rangle + \frac{4}{5}|1\rangle$. What are the probabilities of measuring $|+\rangle$ and $|-\rangle$ in the Hadamard basis?

First, express $|\psi\rangle$ in the Hadamard basis. We need:

$$|\psi\rangle = c_+|+\rangle + c_-|-\rangle$$

where $c_+ = \langle+|\psi\rangle$ and $c_- = \langle-|\psi\rangle$.

$$c_+ = \langle+|\psi\rangle = \frac{1}{\sqrt{2}}(\langle 0| + \langle 1|)\left(\frac{3}{5}|0\rangle + \frac{4}{5}|1\rangle\right) = \frac{1}{\sqrt{2}}\left(\frac{3}{5} + \frac{4}{5}\right) = \frac{7}{5\sqrt{2}}$$

$$c_- = \langle-|\psi\rangle = \frac{1}{\sqrt{2}}(\langle 0| - \langle 1|)\left(\frac{3}{5}|0\rangle + \frac{4}{5}|1\rangle\right) = \frac{1}{\sqrt{2}}\left(\frac{3}{5} - \frac{4}{5}\right) = \frac{-1}{5\sqrt{2}}$$

$$p(+) = |c_+|^2 = \frac{49}{50} = 0.98, \quad p(-) = |c_-|^2 = \frac{1}{50} = 0.02$$

Verification: $0.98 + 0.02 = 1$ ✓

2.6.3 The Measurement Postulate in Full Generality

For a general measurement described by a set of measurement operators $\{M_m\}$ satisfying the completeness relation $\sum_m M_m^\dagger M_m = I$, the probability of outcome $m$ when measuring state $|\psi\rangle$ is:

$$p(m) = \langle\psi|M_m^\dagger M_m|\psi\rangle$$

and the post-measurement state is:

$$\frac{M_m|\psi\rangle}{\sqrt{p(m)}}$$

For projective measurements (which are what we'll primarily use), $M_m = P_m$ are orthogonal projectors satisfying $P_m P_n = \delta_{mn} P_m$ and $\sum_m P_m = I$.

Try It Yourself: Consider measuring a qubit in state $|\psi\rangle = \frac{1}{\sqrt{3}}|0\rangle + \sqrt{\frac{2}{3}}e^{i\pi/4}|1\rangle$ in the $Y$-basis $\{|+i\rangle, |-i\rangle\}$. Compute the probabilities of each outcome. (Hint: First express $|+i\rangle$ and $|-i\rangle$ in the computational basis, then compute the inner products.)


2.7 Qiskit: Creating and Measuring a Qubit in Superposition

Let's write our first quantum program. We'll create a qubit in the $|0\rangle$ state, apply a Hadamard gate to put it in equal superposition, and measure it.

from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
from qiskit.visualization import plot_histogram
import matplotlib.pyplot as plt

# Create a quantum circuit with 1 qubit and 1 classical bit
qc = QuantumCircuit(1, 1)

# Apply Hadamard gate to put the qubit in superposition
# |0⟩ --H--> |+⟩ = (|0⟩ + |1⟩)/√2
qc.h(0)

# Measure the qubit in the computational basis
qc.measure(0, 0)

# Draw the circuit
print(qc.draw(output='text'))

# Simulate
simulator = AerSimulator()
compiled_circuit = transpile(qc, simulator)
job = simulator.run(compiled_circuit, shots=1024)
result = job.result()
counts = result.get_counts()

print(f"\nMeasurement results (1024 shots):")
print(counts)
print(f"Probability of |0⟩: {counts.get('0', 0) / 1024:.3f}")
print(f"Probability of |1⟩: {counts.get('1', 0) / 1024:.3f}")

# Plot histogram
plot_histogram(counts)
plt.show()

Expected output (approximate):

     ┌───┐┌─┐
  q: ┤ H ├┤M├
     └───┘└╥┘
c: 1/══════╩═
           0 

Measurement results (1024 shots):
{'0': 512, '1': 512}
Probability of |0⟩: 0.500
Probability of |1⟩: 0.500

The Hadamard gate $H$ transforms the computational basis states as:

$$H|0\rangle = \frac{|0\rangle + |1\rangle}{\sqrt{2}} = |+\rangle$$ $$H|1\rangle = \frac{|0\rangle - |1\rangle}{\sqrt{2}} = |-\rangle$$

Its matrix representation is:

$$H = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix}$$

2.7.1 Qiskit: Preparing Arbitrary Qubit States

We can prepare any single-qubit state using the $U_3$ gate (or equivalently, a sequence of $R_y$ and $R_z$ rotations). Let's prepare the state $|\psi\rangle = \cos(\theta/2)|0\rangle + e^{i\phi}\sin(\theta/2)|1\rangle$ for arbitrary $\theta$ and $\phi$:

from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
from qiskit.quantum_info import Statevector
import numpy as np

# Prepare |ψ⟩ = cos(θ/2)|0⟩ + e^(iφ)sin(θ/2)|1⟩
# For θ = π/3, φ = π/4
theta = np.pi / 3
phi = np.pi / 4

qc = QuantumCircuit(1)

# Method: R_y(θ) rotates |0⟩ → cos(θ/2)|0⟩ + sin(θ/2)|1⟩
# Then R_z(φ) adds the phase e^(iφ) to |1⟩
# But R_z acts as: |0⟩ → |0⟩, |1⟩ → e^(iφ)|1⟩ ... wait, that's not right.
# Actually R_z(φ)|0⟩ = e^(-iφ/2)|0⟩ and R_z(φ)|1⟩ = e^(iφ/2)|1⟩
# We need to use P gate after the rotation.

# Step 1: R_y(θ) to set amplitudes
qc.ry(theta, 0)

# Step 2: P(φ) = R_z(φ) up to global phase, applied to add relative phase
qc.p(phi, 0)

# Get the statevector
state = Statevector.from_instruction(qc)
print(f"Prepared state: {state.data}")
print(f"Expected: cos(θ/2) = {np.cos(theta/2):.4f}")
print(f"Expected: e^(iφ)sin(θ/2) = {np.exp(1j*phi)*np.sin(theta/2):.4f}")

# Verify Bloch sphere coordinates
from qiskit.visualization import plot_bloch_multivector
plot_bloch_multivector(state)
plt.show()

2.7.2 Qiskit: Demonstrating the Double Hadamard

This example demonstrates that applying two Hadamard gates returns a qubit to its original state—a beautiful demonstration of quantum interference:

from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator

# Double Hadamard: H*H = I
qc_double_h = QuantumCircuit(1, 1)
qc_double_h.h(0)   # First H: |0⟩ → |+⟩
qc_double_h.h(0)   # Second H: |+⟩ → |0⟩ (interference!)
qc_double_h.measure(0, 0)

simulator = AerSimulator()
result = simulator.run(transpile(qc_double_h, simulator), shots=10000).result()
counts = result.get_counts()
print(f"Double Hadamard results: {counts}")
print(f"Expected: ~100% '0' (H² = I)")

# Compare with: single Hadamard (random outcome)
qc_single_h = QuantumCircuit(1, 1)
qc_single_h.h(0)
qc_single_h.measure(0, 0)

result2 = simulator.run(transpile(qc_single_h, simulator), shots=10000).result()
counts2 = result2.get_counts()
print(f"\nSingle Hadamard results: {counts2}")
print(f"Expected: ~50% '0', ~50% '1'")

# Now try: H-Z-H (should flip to |1⟩)
qc_hzh = QuantumCircuit(1, 1)
qc_hzh.h(0)
qc_hzh.z(0)    # Z flips the phase of |1⟩
qc_hzh.h(0)    # Second H converts phase flip to bit flip
qc_hzh.measure(0, 0)

result3 = simulator.run(transpile(qc_hzh, simulator), shots=10000).result()
counts3 = result3.get_counts()
print(f"\nH-Z-H results: {counts3}")
print(f"Expected: ~100% '1' (HZH = X)")

Expected output:

Double Hadamard results: {'0': 10000}
Expected: ~100% '0' (H² = I)

Single Hadamard results: {'0': 4983, '1': 5017}
Expected: ~50% '0', ~50% '1'

H-Z-H results: {'1': 10000}
Expected: ~100% '1' (HZH = X)

2.8 Visualizing on the Bloch Sphere with Qiskit

We can visualize qubit states on the Bloch sphere using Qiskit's visualization tools:

from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
from qiskit import QuantumCircuit
import matplotlib.pyplot as plt

# Create a circuit that prepares |+⟩
qc_plus = QuantumCircuit(1)
qc_plus.h(0)

# Get the statevector
state_plus = Statevector.from_instruction(qc_plus)
print(f"State |+⟩ = {state_plus.data}")

# Plot on Bloch sphere
plot_bloch_multivector(state_plus)
plt.show()

# Now create |+i⟩ = (|0⟩ + i|1⟩)/√2
qc_plus_i = QuantumCircuit(1)
qc_plus_i.h(0)       # First go to |+⟩
qc_plus_i.s(0)       # S gate adds phase: |+⟩ → (|0⟩ + i|1⟩)/√2

state_plus_i = Statevector.from_instruction(qc_plus_i)
print(f"\nState |+i⟩ = {state_plus_i.data}")

plot_bloch_multivector(state_plus_i)
plt.show()

The $S$ gate (phase gate) is:

$$S = \begin{pmatrix} 1 & 0 \\ 0 & i \end{pmatrix}$$

Applying $S$ to $|+\rangle$:

$$S|+\rangle = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & 0 \\ 0 & i \end{pmatrix}\begin{pmatrix} 1 \\ 1 \end{pmatrix} = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 \\ i \end{pmatrix} = \frac{|0\rangle + i|1\rangle}{\sqrt{2}} = |+i\rangle$$

2.8.1 Qiskit: Visualizing Gate Sequences on the Bloch Sphere

Let's trace a sequence of gates and see how the state moves on the Bloch sphere:

from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.visualization import plot_bloch_multivector
import numpy as np

# Trace the state through a sequence of gates
states = []
labels = []

# Initial state |0⟩
qc = QuantumCircuit(1)
states.append(Statevector.from_instruction(qc))
labels.append('|0⟩')

# After H gate: |+⟩
qc.h(0)
states.append(Statevector.from_instruction(qc))
labels.append('|+⟩')

# After T gate: T|+⟩ = (|0⟩ + e^(iπ/4)|1⟩)/√2
qc.t(0)
states.append(Statevector.from_instruction(qc))
labels.append('T|+⟩')

# After another H gate
qc.h(0)
states.append(Statevector.from_instruction(qc))
labels.append('HTH|0⟩')

# Print states
for label, state in zip(labels, states):
    print(f"{label}: {state.data}")

# Visualize each state on the Bloch sphere
fig, axes = plt.subplots(1, len(states), figsize=(4*len(states), 4))
for i, (state, label) in enumerate(zip(states, labels)):
    plot_bloch_multivector(state, ax=axes[i] if len(states) > 1 else axes)
    axes[i].set_title(label) if len(states) > 1 else axes.set_title(label)
plt.tight_layout()
plt.show()

2.9 The State Vector and Density Matrix

For a pure state $|\psi\rangle$, the density matrix (or density operator) is:

$$\rho = |\psi\rangle\langle\psi|$$

For $|\psi\rangle = \alpha|0\rangle + \beta|1\rangle$:

$$\rho = \begin{pmatrix} \alpha \\ \beta \end{pmatrix}\begin{pmatrix} \alpha^* & \beta^* \end{pmatrix} = \begin{pmatrix} |\alpha|^2 & \alpha\beta^* \\ \alpha^*\beta & |\beta|^2 \end{pmatrix}$$

The diagonal elements are the probabilities of measuring $|0\rangle$ and $|1\rangle$. The off-diagonal elements are the coherences—they encode the phase relationship between the basis states and are what distinguish a coherent superposition from a classical mixture.

A classical probabilistic mixture of $|0\rangle$ and $|1\rangle$ (e.g., a coin flip that prepares $|0\rangle$ with probability $p$ and $|1\rangle$ with probability $1-p$) has density matrix:

$$\rho_{\text{classical}} = p|0\rangle\langle 0| + (1-p)|1\rangle\langle 1| = \begin{pmatrix} p & 0 \\ 0 & 1-p \end{pmatrix}$$

The off-diagonal zeros mean no interference is possible. This is the mathematical distinction between "quantum superposition" and "classical uncertainty."

import numpy as np

# Density matrix for |+⟩
alpha = 1/np.sqrt(2)
beta = 1/np.sqrt(2)
rho_plus = np.array([[abs(alpha)**2, alpha*np.conj(beta)],
                      [alpha.conj()*beta, abs(beta)**2]])
print("Density matrix for |+⟩:")
print(rho_plus)
print(f"Trace: {np.trace(rho_plus)}")  # Should be 1

# Classical mixture: 50% |0⟩, 50% |1⟩
rho_classical = np.array([[0.5, 0.0],
                           [0.0, 0.5]])
print("\nClassical mixture (50-50):")
print(rho_classical)
print(f"Trace: {np.trace(rho_classical)}")

# Compute purity: Tr(ρ²)
purity_plus = np.trace(rho_plus @ rho_plus).real
purity_classical = np.trace(rho_classical @ rho_classical).real
print(f"\nPurity of |+⟩: {purity_plus:.4f}")  # Should be 1
print(f"Purity of classical mixture: {purity_classical:.4f}")  # Should be 0.5

Output:

Density matrix for |+⟩:
[[0.5+0.j 0.5+0.j]
 [0.5+0.j 0.5+0.j]]
Trace: (1+0j)

Classical mixture (50-50):
[[0.5 0. ]
 [0.  0.5]]
Trace: 1.0

Purity of |+⟩: 1.0000
Purity of classical mixture: 0.5000

Both have the same diagonal (50-50 measurement probabilities), but the quantum state has non-zero off-diagonal elements—it can exhibit interference. The classical mixture cannot.

2.9.1 Properties of the Density Matrix

The density matrix $\rho$ has the following key properties:

  1. Hermitian: $\rho = \rho^\dagger$
  2. Positive semidefinite: $\langle\psi|\rho|\psi\rangle \geq 0$ for all $|\psi\rangle$
  3. Unit trace: $\text{Tr}(\rho) = 1$
  4. Purity: $\text{Tr}(\rho^2) \leq 1$, with equality if and only if $\rho$ represents a pure state

Worked Example: Compute the density matrix for $|\psi\rangle = \frac{1}{\sqrt{3}}|0\rangle + \sqrt{\frac{2}{3}}e^{i\pi/4}|1\rangle$ and verify its properties.

$$\rho = |\psi\rangle\langle\psi| = \begin{pmatrix} 1/3 \\ \sqrt{2/3}e^{i\pi/4} \end{pmatrix}\begin{pmatrix} 1/3 & \sqrt{2/3}e^{-i\pi/4} \end{pmatrix}$$

Wait, let me be more careful. $\alpha = \frac{1}{\sqrt{3}}$, $\beta = \sqrt{\frac{2}{3}}e^{i\pi/4}$.

$$\rho = \begin{pmatrix} |\alpha|^2 & \alpha\beta^* \\ \alpha^*\beta & |\beta|^2 \end{pmatrix} = \begin{pmatrix} \frac{1}{3} & \frac{1}{\sqrt{3}}\sqrt{\frac{2}{3}}e^{-i\pi/4} \\ \frac{1}{\sqrt{3}}\sqrt{\frac{2}{3}}e^{i\pi/4} & \frac{2}{3} \end{pmatrix} = \begin{pmatrix} \frac{1}{3} & \frac{\sqrt{2}}{3}e^{-i\pi/4} \\ \frac{\sqrt{2}}{3}e^{i\pi/4} & \frac{2}{3} \end{pmatrix}$$

Verification: - Hermitian: $\rho_{12}^* = \frac{\sqrt{2}}{3}e^{-i\pi/4} \cdot e^{-i\cdot 0} = ?$ ... Actually, $\rho_{21} = \frac{\sqrt{2}}{3}e^{i\pi/4} = (\frac{\sqrt{2}}{3}e^{-i\pi/4})^* = \rho_{12}^*$ ✓ - Unit trace: $\frac{1}{3} + \frac{2}{3} = 1$ ✓ - Purity: $\text{Tr}(\rho^2) = \frac{1}{9} + \frac{\sqrt{2}}{3}\cdot\frac{\sqrt{2}}{3}e^{-i\pi/4}e^{i\pi/4} + \frac{\sqrt{2}}{3}e^{i\pi/4}\frac{\sqrt{2}}{3}e^{-i\pi/4} + \frac{4}{9}$ ... This is getting complex. Let me just verify that since this is a pure state, $\text{Tr}(\rho^2) = 1$.

Since $\rho = |\psi\rangle\langle\psi|$ is a rank-1 projector, $\rho^2 = |\psi\rangle\langle\psi|\psi\rangle\langle\psi| = |\psi\rangle\langle\psi| = \rho$ (since $\langle\psi|\psi\rangle = 1$). Therefore $\text{Tr}(\rho^2) = \text{Tr}(\rho) = 1$ ✓

2.9.2 Mixed States: A Deeper Look

A mixed state is a statistical ensemble of pure states:

$$\rho = \sum_i p_i |\psi_i\rangle\langle\psi_i|$$

where $p_i \geq 0$ and $\sum_i p_i = 1$. This represents classical uncertainty about which pure state the system is in.

Key distinction: A pure state $|+\rangle = \frac{1}{\sqrt{2}}(|0\rangle + |1\rangle)$ and the mixed state $\frac{1}{2}|0\rangle\langle 0| + \frac{1}{2}|1\rangle\langle 1|$ give the same measurement probabilities in the computational basis (both give 50-50), but they are fundamentally different:

  1. Measuring in the Hadamard basis, $|+\rangle$ gives $|+\rangle$ with certainty, while the mixed state gives $|+\rangle$ with probability 1/2 and $|-\rangle$ with probability 1/2.
  2. $|+\rangle$ can exhibit interference; the mixed state cannot.
  3. The purity of $|+\rangle$ is $\text{Tr}(\rho^2) = 1$; the purity of the mixed state is $\text{Tr}(\rho^2) = 0.5$.

Common Misconception: "A qubit in superposition $\alpha|0\rangle + \beta|1\rangle$ is the same as a probabilistic mixture of $|0\rangle$ and $|1\rangle$." This is wrong. The superposition has off-diagonal elements (coherences) in the density matrix, enabling interference effects. The mixture has only diagonal elements. They can always be distinguished by measuring in a basis other than the computational basis.


2.10 Multiple Qubits: A Preview

With $n$ qubits, the state space is the tensor product of $n$ copies of $\mathbb{C}^2$, giving a $2^n$-dimensional space. A general $n$-qubit state is:

$$|\psi\rangle = \sum_{x \in \{0,1\}^n} \alpha_x |x\rangle$$

where $\sum_x |\alpha_x|^2 = 1$.

For two qubits, the computational basis states are:

$$|00\rangle, |01\rangle, |10\rangle, |11\rangle$$

A general two-qubit state is:

$$|\psi\rangle = \alpha_{00}|00\rangle + \alpha_{01}|01\rangle + \alpha_{10}|10\rangle + \alpha_{11}|11\rangle$$

The Bloch sphere only works for single qubits. For multiple qubits, the geometry is far richer and includes entanglement—states that cannot be factored as a product of individual qubit states. We will explore this in depth in later chapters.

2.10.1 The Exponential State Space

The exponential growth of the state space is the source of quantum computing's power—and its challenge. Let's make this concrete:

Qubits State vector size Memory (at 128 bits/amplitude)
1 2 32 bytes
10 1,024 16 KB
20 ~1 million 16 MB
30 ~1 billion 16 GB
50 ~$10^{15}$ 16 PB
100 ~$10^{30}$ $10^{22}$ GB

At 50 qubits, we're already beyond the memory of any classical computer. At 100 qubits, we'd need more memory than exists on Earth. This is why classical simulation of quantum computers becomes infeasible, and why quantum computers with even a modest number of high-quality qubits can perform computations that are classically intractable.

Recurring Theme: We're at the beginning. Classical computers had a 75-year head start. Quantum computers are at the equivalent of the 1940s for classical computing. The hardware is noisy, the software is immature, and the algorithms are still being discovered. But the exponential state space guarantees that there is computational power waiting to be unlocked.


2.11 Physical Implementations of Qubits

A qubit is an abstract mathematical object, but it must be realized in a physical system. Here are the leading qubit technologies:

2.11.1 Superconducting Qubits

Used by IBM, Google, and others. Superconducting circuits at millikelvin temperatures form Josephson junctions that behave as nonlinear oscillators with two accessible energy levels. Advantages: fast gate times (~10-100 ns), microchip fabrication. Disadvantages: require extreme cooling (~15 mK), limited coherence times (~100 μs).

2.11.2 Trapped Ion Qubits

Used by IonQ, Quantinuum, and others. Individual ions are trapped in electromagnetic fields and manipulated with laser pulses. Advantages: very high gate fidelities (99.9%+), long coherence times (seconds). Disadvantages: slower gate times (~10 μs), scaling challenges.

2.11.3 Photonic Qubits

Used by Xanadu, PsiQuantum, and others. Quantum information is encoded in the polarization or path of single photons. Advantages: room-temperature operation, natural for quantum communication. Disadvantages: hard to make photons interact (needed for 2-qubit gates), probabilistic gate operations.

2.11.4 Other Approaches

  • Topological qubits (Microsoft): Encode information in non-Abelian anyons, which are inherently protected from local errors. Still in development.
  • Neutral atom qubits (QuEra, Pasqal): Use arrays of individual atoms trapped in optical tweezers. Recently demonstrated over 1,000 qubits.
  • Silicon spin qubits (Intel): Use the spin of individual electrons in silicon. Compatible with semiconductor fabrication, but challenging to control.
  Qubit Technology Comparison:

  ┌──────────────────┬─────────────┬──────────────┬────────────────┐
  │ Technology        │ Gate Time   │ Coherence     │ Scalability    │
  ├──────────────────┼─────────────┼──────────────┼────────────────┤
  │ Superconducting  │ 10-100 ns   │ ~100 μs      │ Good (fabrication)│
  │ Trapped Ion      │ ~10 μs      │ ~10 s        │ Moderate       │
  │ Photonic         │ ~ns         │ N/A (travel) │ Moderate       │
  │ Neutral Atom     │ ~1 μs       │ ~1 s         │ Good (arrays)  │
  │ Silicon Spin     │ ~100 ns     │ ~1 ms        │ Good (CMOS)    │
  │ Topological      │ ???         │ ???          │ Unknown        │
  └──────────────────┴─────────────┴──────────────┴────────────────┘

Recurring Theme: Noise is the enemy. Every qubit technology has tradeoffs between gate speed, coherence time, and scalability. There is no clear winner yet—the field is still searching for the "transistor of quantum computing."


2.12 The Single-Qubit Gate Set

Any unitary operation on a single qubit can be decomposed into a sequence of rotations about the axes of the Bloch sphere. This is a powerful result: it means that any single-qubit quantum gate can be built from a small set of primitive operations.

2.12.1 The Pauli Gates

The three Pauli gates are rotations by $\pi$ about the three axes of the Bloch sphere:

$$X = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}, \quad Y = \begin{pmatrix} 0 & -i \\ i & 0 \end{pmatrix}, \quad Z = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}$$

The X gate (bit flip): $X|0\rangle = |1\rangle$, $X|1\rangle = |0\rangle$. This flips the qubit from 0 to 1 or vice versa, analogous to the classical NOT gate. On the Bloch sphere, it's a $\pi$ rotation about the x-axis.

The Y gate (bit-and-phase flip): $Y|0\rangle = i|1\rangle$, $Y|1\rangle = -i|0\rangle$. This combines a bit flip with a phase flip. On the Bloch sphere, it's a $\pi$ rotation about the y-axis.

The Z gate (phase flip): $Z|0\rangle = |0\rangle$, $Z|1\rangle = -|1\rangle$. This flips the phase of $|1\rangle$ while leaving $|0\rangle$ unchanged. On the Bloch sphere, it's a $\pi$ rotation about the z-axis.

Worked Example: Compute $Z|+\rangle$ and $Z|-\rangle$.

$$Z|+\rangle = Z\left(\frac{|0\rangle + |1\rangle}{\sqrt{2}}\right) = \frac{Z|0\rangle + Z|1\rangle}{\sqrt{2}} = \frac{|0\rangle - |1\rangle}{\sqrt{2}} = |-\rangle$$

$$Z|-\rangle = Z\left(\frac{|0\rangle - |1\rangle}{\sqrt{2}}\right) = \frac{|0\rangle + |1\rangle}{\sqrt{2}} = |+\rangle$$

So the Z gate swaps $|+\rangle$ and $|-\rangle$, just as the X gate swaps $|0\rangle$ and $|1\rangle$. This is because Z is a rotation about the z-axis, which flips the x-component of the Bloch vector.

2.12.2 The Hadamard Gate

$$H = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix}$$

The Hadamard gate is arguably the most important single-qubit gate. It creates superpositions from computational basis states and vice versa:

$$H|0\rangle = |+\rangle, \quad H|1\rangle = |-\rangle, \quad H|+\rangle = |0\rangle, \quad H|-\rangle = |1\rangle$$

On the Bloch sphere, $H$ is a rotation by $\pi$ about the axis $(\hat{x} + \hat{z})/\sqrt{2}$, which swaps the x- and z-axes. This is why it converts between the computational basis (Z eigenstates) and the Hadamard basis (X eigenstates).

Key property: $H^2 = I$ (the Hadamard gate is its own inverse). Applying H twice returns the qubit to its original state, which we demonstrated earlier through interference.

2.12.3 Phase Gates

The phase gates introduce relative phases between $|0\rangle$ and $|1\rangle$:

$$S = \begin{pmatrix} 1 & 0 \\ 0 & i \end{pmatrix} = R_z(\pi/2), \quad T = \begin{pmatrix} 1 & 0 \\ 0 & e^{i\pi/4} \end{pmatrix} = R_z(\pi/4)$$

The $S$ gate (also called the $\sqrt{Z}$ gate since $S^2 = Z$) applies a phase of $i$ to $|1\rangle$. The $T$ gate (also called the $\pi/8$ gate for historical reasons) applies a phase of $e^{i\pi/4}$ to $|1\rangle$.

Worked Example: Compute $TH|0\rangle$ step by step.

Step 1: $H|0\rangle = |+\rangle = \frac{1}{\sqrt{2}}(|0\rangle + |1\rangle)$

Step 2: $T|+\rangle = T\left(\frac{1}{\sqrt{2}}(|0\rangle + |1\rangle)\right) = \frac{1}{\sqrt{2}}(T|0\rangle + T|1\rangle) = \frac{1}{\sqrt{2}}(|0\rangle + e^{i\pi/4}|1\rangle)$

So $TH|0\rangle = \frac{1}{\sqrt{2}}(|0\rangle + e^{i\pi/4}|1\rangle)$. On the Bloch sphere, this state has $\theta = \pi/2$ and $\phi = \pi/4$—it's a point on the equator, rotated $\pi/4$ from the positive x-axis.

2.12.4 The Universal Single-Qubit Gate Decomposition

Theorem (Z-Y decomposition): Any single-qubit unitary $U$ can be written as:

$$U = e^{i\alpha} R_z(\beta) R_y(\gamma) R_z(\delta)$$

for some angles $\alpha, \beta, \gamma, \delta \in \mathbb{R}$.

This means any single-qubit quantum operation can be implemented using at most three rotations (two Z-rotations and one Y-rotation) plus a global phase. Since the global phase is physically irrelevant, any single-qubit gate requires at most three elementary rotations.

Corollary: Any single-qubit unitary can be implemented using only $H$ and $T$ gates, along with the identity. This is because $H$ and $T$ are sufficient to approximate any rotation arbitrarily well (the Solovay-Kitaev theorem guarantees efficient approximation).

# Verify the Z-Y decomposition for an arbitrary unitary
from scipy.linalg import expm
import numpy as np

# Create a random unitary
theta = np.pi / 3
phi = np.pi / 5
lam = np.pi / 7

# U = Rz(θ)Ry(φ)Rz(λ) (up to global phase)
Z = np.array([[1, 0], [0, -1]], dtype=complex)
Y = np.array([[0, -1j], [1j, 0]], dtype=complex)
I = np.eye(2, dtype=complex)

Rz_theta = expm(-1j * theta/2 * Z)
Ry_phi = expm(-1j * phi/2 * Y)
Rz_lam = expm(-1j * lam/2 * Z)

U = Rz_theta @ Ry_phi @ Rz_lam
print("Decomposed unitary:")
print(U)

# Verify unitarity
print("\nUnitary?", np.allclose(U.conj().T @ U, I))

2.12.5 Qiskit: Building Circuits with Single-Qubit Gates

from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
from qiskit.quantum_info import Statevector
import numpy as np

# Create circuits for each single-qubit gate
gates = {
    'X': QuantumCircuit(1),
    'Y': QuantumCircuit(1),
    'Z': QuantumCircuit(1),
    'H': QuantumCircuit(1),
    'S': QuantumCircuit(1),
    'T': QuantumCircuit(1),
}

# Apply gates
gates['X'].x(0)
gates['Y'].y(0)
gates['Z'].z(0)
gates['H'].h(0)
gates['S'].s(0)
gates['T'].t(0)

# For each gate, start from |0⟩, apply the gate, and show the resulting state
for name, qc in gates.items():
    state = Statevector.from_instruction(qc)
    print(f"{name}|0⟩ = {state.data}")

# More interesting: start from |+⟩, apply each gate
print("\n--- Gates applied to |+⟩ ---")
for name in ['X', 'Y', 'Z', 'S', 'T']:
    qc = QuantumCircuit(1)
    qc.h(0)  # Prepare |+⟩
    getattr(qc, name.lower())(0)  # Apply gate
    state = Statevector.from_instruction(qc)
    print(f"{name}|+⟩ = {state.data}")

2.13 Quantum Gates as Rotations: A Unified View

All single-qubit gates can be understood as rotations of the Bloch sphere. This geometric perspective unifies everything we've learned about gates.

2.13.1 The General Rotation Gate

The most general single-qubit rotation is:

$$R_{\hat{n}}(\theta) = e^{-i\theta\hat{n}\cdot\vec{\sigma}/2} = \cos\frac{\theta}{2}I - i\sin\frac{\theta}{2}(\hat{n}\cdot\vec{\sigma})$$

where $\hat{n} = (n_x, n_y, n_z)$ is a unit vector specifying the rotation axis, $\vec{\sigma} = (X, Y, Z)$ is the vector of Pauli matrices, and $\theta$ is the rotation angle.

This rotates the Bloch vector by angle $\theta$ about the axis $\hat{n}$. The factor of 1/2 in the exponent comes from the fact that qubits are spin-1/2 objects—a physical rotation of $2\pi$ corresponds to a $4\pi$ rotation on the Bloch sphere.

2.13.2 Connecting Gates to Rotations

Gate Rotation Angle
$I$ $R_{\hat{n}}(0)$ 0
$X$ $R_x(\pi)$ $\pi$ about x-axis
$Y$ $R_y(\pi)$ $\pi$ about y-axis
$Z$ $R_z(\pi)$ $\pi$ about z-axis
$H$ $R_{(\hat{x}+\hat{z})/\sqrt{2}}(\pi)$ $\pi$ about $(x+z)/\sqrt{2}$
$S$ $R_z(\pi/2)$ $\pi/2$ about z-axis
$T$ $R_z(\pi/4)$ $\pi/4$ about z-axis

2.13.3 Commutation and Non-Commutation of Rotations

Rotations about different axes do not generally commute. This is a fundamental property of quantum mechanics and the origin of the uncertainty principle.

Worked Example: Show that $R_x(\pi/2)$ and $R_z(\pi/2)$ do not commute.

$$R_x(\pi/2) = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & -i \\ -i & 1 \end{pmatrix}$$

$$R_z(\pi/2) = \begin{pmatrix} e^{-i\pi/4} & 0 \\ 0 & e^{i\pi/4} \end{pmatrix}$$

Computing $R_x(\pi/2) R_z(\pi/2)$ and $R_z(\pi/2) R_x(\pi/2)$ and comparing (left as an exercise), you'll find they differ by a phase. The non-commutation of rotations on different axes is what makes quantum circuits powerful—sequences of non-commuting gates can generate arbitrary rotations, enabling universal quantum computation.

Try It Yourself: Compute $R_x(\pi/2) R_z(\pi/2)|0\rangle$ and $R_z(\pi/2) R_x(\pi/2)|0\rangle$ and verify they produce different states. This is a concrete demonstration that the order of quantum gates matters—you cannot freely rearrange a quantum circuit.


2.14 Quantum Measurement in Depth

2.14.1 Projective Measurements

A projective measurement is described by a set of orthogonal projectors $\{P_m\}$ that sum to the identity: $\sum_m P_m = I$. When measuring state $|\psi\rangle$:

  • Outcome $m$ occurs with probability $p(m) = \langle\psi|P_m|\psi\rangle$
  • Post-measurement state: $\frac{P_m|\psi\rangle}{\sqrt{p(m)}}$

For measurement in the computational basis, $P_0 = |0\rangle\langle 0|$ and $P_1 = |1\rangle\langle 1|$.

For measurement in the Hadamard basis, $P_+ = |+\rangle\langle +|$ and $P_- = |-\rangle\langle -|$.

2.14.2 POVM Measurements (Brief Introduction)

A more general framework is the Positive Operator-Valued Measure (POVM). A POVM is a set of positive semidefinite operators $\{E_m\}$ satisfying $\sum_m E_m = I$. Unlike projective measurements, the POVM elements need not be orthogonal, and the number of outcomes can exceed the dimension of the Hilbert space.

POVMs are important in quantum information theory because they provide the most general framework for quantum measurements. They arise naturally in scenarios where the measurement apparatus cannot distinguish all possible states, or when we want to extract partial information without collapsing the state completely.

Example: Consider a qubit that is known to be in either state $|0\rangle$ or state $|+\rangle$, and we want to determine which. A POVM with three elements can distinguish these states with zero error—something that is impossible with projective measurement alone:

$$E_1 = \frac{\sqrt{2}}{1+\sqrt{2}}|1\rangle\langle 1|, \quad E_2 = \frac{\sqrt{2}}{1+\sqrt{2}}|-\rangle\langle -|, \quad E_3 = I - E_1 - E_2$$

  • If outcome 1 occurs, the state was definitely $|+\rangle$ (since $|0\rangle$ has zero overlap with $|1\rangle$).
  • If outcome 2 occurs, the state was definitely $|0\rangle$ (since $|+\rangle$ has zero overlap with $|-\rangle$).
  • If outcome 3 occurs, the measurement is inconclusive.

2.14.3 Measurement Disturbance

Measurement in quantum mechanics is inherently disturbing. After a projective measurement, the state collapses to an eigenstate of the measured observable, destroying any information about other incompatible observables.

Example: If a qubit is in state $|+\rangle$ and we measure it in the computational basis, we get outcome 0 with probability 1/2 and outcome 1 with probability 1/2. After measurement, the state is either $|0\rangle$ or $|1\rangle$—the original superposition is destroyed. We have gained information about the Z observable (whether the qubit is closer to $|0\rangle$ or $|1\rangle$) but lost all information about the X observable (the phase relationship).

This is a manifestation of the uncertainty principle: non-commuting observables cannot be simultaneously measured with arbitrary precision. For a qubit, $X$ and $Z$ do not commute: $[X, Z] = -2iY \neq 0$. If we know the state's Z-component precisely, the X-component is maximally uncertain, and vice versa.

Common Misconception: "Quantum measurement always destroys the quantum state." This is true for projective measurements on unknown states, but not always. If the state happens to be an eigenstate of the measured observable, measurement leaves it unchanged. Moreover, weak measurements can extract partial information with only partial disturbance, and quantum non-demolition measurements can measure an observable without disturbing it.


2.15 Historical Context: From Stern-Gerlach to Qubits

The qubit has deep historical roots in the development of quantum mechanics.

1922 — Stern-Gerlach experiment: Otto Stern and Walther Gerlach passed silver atoms through an inhomogeneous magnetic field. They observed that the beam split into exactly two components, corresponding to the two possible spin states of the silver atom's outermost electron. This was the first direct observation of quantized angular momentum—what we now recognize as a two-level quantum system, or qubit.

1925-1926 — Matrix mechanics and wave mechanics: Heisenberg, Born, and Jordan develop matrix mechanics, while Schrödinger develops wave mechanics. These are later shown to be equivalent formulations of quantum theory, both ultimately resting on the linear algebra of Hilbert spaces.

1927 — Spin formalism: Pauli introduces the spin matrices (now called Pauli matrices) to describe the internal angular momentum of electrons. The Pauli matrices $\sigma_x, \sigma_y, \sigma_z$ become the fundamental operators for single-qubit systems.

1932 — Von Neumann's mathematical formulation: John von Neumann provides the rigorous Hilbert space formulation of quantum mechanics, establishing the mathematical framework (states as vectors, observables as Hermitian operators, time evolution as unitary operators) that we still use today.

1983 — Qubit terminology coined: Benjamin Schumacher introduces the term "qubit" in a 1995 paper, though the concept had been used since the early days of quantum information theory. The term was actually suggested to Schumacher by William Wootters in a conversation, playing on the word "bit."

1995 — First quantum error correction: Peter Shor and Andrew Steane independently discover quantum error-correcting codes, showing that quantum information can be protected from noise—a result that was not obvious given the no-cloning theorem and the continuous nature of quantum errors.

1997 — First experimental quantum gates: The first two-qubit quantum gates are demonstrated experimentally using trapped ions (Monroe et al.) and NMR (Gershenfeld and Chuang), marking the beginning of experimental quantum computing.

Why This Matters: The qubit is not an abstract mathematical curiosity—it is grounded in over a century of experimental physics. Every concept in this chapter (superposition, measurement, the Bloch sphere) has been verified by experiments going back to the 1920s. The mathematics we're learning is not just a convenient formalism; it is a precise description of nature.


2.16 The Connection Between Qubits and Spin-1/2 Particles

The mathematics of qubits is identical to the mathematics of spin-1/2 particles in quantum mechanics. This is not a coincidence—it reflects a deep connection between information and physics.

A spin-1/2 particle (like an electron) has two possible spin states along any axis: spin-up and spin-down. These correspond to $|0\rangle$ and $|1\rangle$ in our qubit notation. The Bloch sphere representation of qubit states is the same as the spin state space of a spin-1/2 particle.

The Stern-Gerlach experiment (1922) demonstrated this directly. Silver atoms (with one unpaired electron) were sent through an inhomogeneous magnetic field. The beam split into exactly two components—corresponding to the two possible spin states of the electron. This was the first experimental observation of a two-level quantum system.

  Stern-Gerlach Experiment:

  Silver atoms ──────► ┌────┐ ──────► Two beams:
  with spin           │ B  │         spin-up (|0⟩)
                     │field│         spin-down (|1⟩)
                     └────┘

  Key insight: The measurement axis matters!
  Measuring spin along z → two beams (|0⟩_z and |1⟩_z)
  Measuring spin along x → two beams (|+⟩_x and |-⟩_x)

  If we measure along z, get spin-up, then measure along x,
  we get 50/50 outcomes — the z-measurement destroyed
  the x-information. This is the uncertainty principle in action.

Sequential Stern-Gerlach experiments beautifully illustrate quantum measurement:

  1. Pass atoms through a z-oriented Stern-Gerlach device. You get two beams: spin-up ($|0\rangle$) and spin-down ($|1\rangle$) along z.

  2. Block the spin-down beam and pass the spin-up beam through another z-oriented device. Result: 100% spin-up. The first measurement has "prepared" the state $|0\rangle$.

  3. Now pass the spin-up beam through an x-oriented device. Result: 50% spin-up and 50% spin-down along x. The state $|0\rangle_z = \frac{1}{\sqrt{2}}(|+\rangle_x + |-\rangle_x)$ is an equal superposition of x-spin states.

  4. Block the spin-down-x beam and pass the spin-up-x beam through another z-oriented device. Result: 50% spin-up and 50% spin-down along z! The x-measurement has destroyed the z-information.

This sequential measurement scenario is exactly what happens when we measure a qubit in different bases—the mathematics we've developed in this chapter describes it precisely.

2.16.1 The Stern-Gerlach Experiment in Qiskit

We can simulate the Stern-Gerlach experiment using Qiskit:

from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
import numpy as np

simulator = AerSimulator()

# Step 1: Prepare |0⟩ (spin-up along z)
# Step 2: Measure along z → 100% spin-up
qc_zz = QuantumCircuit(1, 1)
# No gates needed — qubit starts in |0⟩
qc_zz.measure(0, 0)
result_zz = simulator.run(transpile(qc_zz, simulator), shots=10000).result()
print("Z-measurement of |0⟩:", result_zz.get_counts())

# Step 3: Measure |0⟩ along x → 50/50
qc_zx = QuantumCircuit(1, 1)
qc_zx.h(0)  # Rotate to x-basis for measurement
qc_zx.measure(0, 0)
result_zx = simulator.run(transpile(qc_zx, simulator), shots=10000).result()
print("X-measurement of |0⟩:", result_zx.get_counts())

# Step 4: Prepare |+⟩ (spin-up along x), then measure along z → 50/50
qc_xz = QuantumCircuit(1, 1)
qc_xz.h(0)  # Prepare |+⟩ (spin-up along x)
qc_xz.measure(0, 0)  # Measure along z
result_xz = simulator.run(transpile(qc_xz, simulator), shots=10000).result()
print("Z-measurement of |+⟩:", result_xz.get_counts())

# Step 5: Prepare |+⟩, measure along x → 100% spin-up
qc_xx = QuantumCircuit(1, 1)
qc_xx.h(0)   # Prepare |+⟩
qc_xx.h(0)    # Rotate to x-basis for measurement (H converts x-basis to z-basis)
qc_xx.measure(0, 0)
result_xx = simulator.run(transpile(qc_xx, simulator), shots=10000).result()
print("X-measurement of |+⟩:", result_xx.get_counts())

This simulation perfectly reproduces the results of the sequential Stern-Gerlach experiments, confirming that our qubit model correctly describes spin-1/2 physics.


2.17 Quantum Key Distribution: An Application of Qubit Measurement

One of the most practical applications of single-qubit physics is quantum key distribution (QKD), specifically the BB84 protocol (named after Bennett and Brassard, 1984). BB84 allows two parties (Alice and Bob) to establish a shared secret key using quantum communication, with security guaranteed by the laws of quantum mechanics.

2.17.1 The BB84 Protocol

Setup: Alice wants to send a random secret key to Bob. She encodes each bit of the key as a qubit in one of two bases:

  • Z-basis (computational basis): 0 → $|0\rangle$, 1 → $|1\rangle$
  • X-basis (Hadamard basis): 0 → $|+\rangle$, 1 → $|-\rangle$

Protocol:

  1. Alice randomly chooses a bit (0 or 1) and a basis (Z or X) for each qubit.
  2. Alice sends the qubit to Bob.
  3. Bob randomly chooses a basis (Z or X) to measure each qubit.
  4. Alice and Bob publicly announce their basis choices (but not the bit values).
  5. They keep only the bits where they chose the same basis (~50% of the time).
  6. They compare a subset of the remaining bits to check for errors (eavesdropping detection).
  BB84 Protocol Example:

  Alice's bits:     0   1   1   0   1   0   0   1
  Alice's bases:    Z   X   Z   X   Z   X   Z   X
  Alice sends:     |0⟩ |−⟩ |1⟩ |+⟩ |1⟩ |+⟩ |0⟩ |−⟩

  Bob's bases:      Z   Z   X   X   Z   Z   X   X
  Bob measures:    |0⟩ |?⟩ |?⟩ |+⟩ |1⟩ |?⟩ |?⟩ |−⟩

  Same basis?      ✓   ✗   ✗   ✓   ✓   ✗   ✗   ✓
  Keep bits:        0   -   -   0   1   -   -   1

  Shared key: 0 1 1

Why BB84 is secure: An eavesdropper (Eve) who intercepts and measures a qubit must choose a basis. If she chooses the wrong basis (which happens 50% of the time), her measurement disturbs the qubit state, introducing errors that Alice and Bob can detect.

Worked Example: Alice sends $|+\rangle$ (bit 1 in X-basis). Eve intercepts and measures in the Z-basis, getting either $|0\rangle$ (50%) or $|1\rangle$ (50%). Suppose Eve gets $|0\rangle$. She now sends $|0\rangle$ to Bob. If Bob measures in the X-basis, he gets $|+\rangle$ or $|-\rangle$ with equal probability. When Alice and Bob compare, there's a 25% error rate (50% chance Eve chose wrong basis × 50% chance that causes an error). This is detectable!

# BB84 simulation
from qiskit import QuantumCircuit, transpile
from qiskit_aer import AerSimulator
import numpy as np

simulator = AerSimulator()
num_qubits = 100

# Alice's random bits and bases
alice_bits = np.random.randint(0, 2, num_qubits)
alice_bases = np.random.randint(0, 2, num_qubits)  # 0 = Z, 1 = X

# Bob's random measurement bases
bob_bases = np.random.randint(0, 2, num_qubits)

# Simulate the protocol
shared_key = []
for i in range(num_qubits):
    qc = QuantumCircuit(1, 1)

    # Alice prepares the qubit
    if alice_bits[i] == 1:
        qc.x(0)
    if alice_bases[i] == 1:
        qc.h(0)

    # Bob measures
    if bob_bases[i] == 1:
        qc.h(0)
    qc.measure(0, 0)

    result = simulator.run(transpile(qc, simulator), shots=1).result()
    bob_bit = int(list(result.get_counts().keys())[0])

    # Keep only if same basis
    if alice_bases[i] == bob_bases[i]:
        shared_key.append(bob_bit)

print(f"Alice sent {num_qubits} qubits")
print(f"Same basis (kept): {len(shared_key)} bits (~{len(shared_key)/num_qubits*100:.0f}%)")
print(f"Shared key: {''.join(map(str, shared_key[:20]))}...")

Recurring Theme: The security of BB84 depends on the fundamental properties of quantum measurement: it is probabilistic, it disturbs the state, and it cannot be copied (no-cloning theorem). Classical encryption cannot offer this level of physical security—BB84's security is guaranteed by the laws of physics, not by computational hardness assumptions.