Gregory Friedman The Greg Wide Web on the name →

Case Study · Quantum · Simulation

Statevectors by Hand

2024– · in progress · repository

The idea

In 2024 my team competed in YQuantum, Yale’s quantum-computing hackathon, on the Classiq track, where you describe a circuit at a high level and a compiler synthesizes the gates. It was exhilarating and slightly hollow at once: the framework was doing the part I most wanted to understand. A quantum circuit is a picture of gates, but the thing that actually computes is the statevector underneath, and a high-level tool keeps that vector politely out of sight. This page is me lifting the lid, the same instinct that runs through every project on this site: if a framework is doing the interesting part, rebuild the interesting part. (The instinct later became a team sport: Qlearn, our senior design quantum-computing classroom, is the same lid-lifting scaled to a full curriculum.)

The object is smaller than its reputation. The state of nn qubits is a single unit vector in 2n2^n complex dimensions, one amplitude per classical outcome. Three qubits is eight amplitudes. A gate is a unitary matrix multiplying that vector, and measurement is the one irreversible step: you sample an outcome with probability equal to the squared magnitude of its amplitude, and the vector collapses onto it. Everything mysterious about quantum computing (superposition, interference, entanglement) is visible in how those eight numbers move.

The plate below is that simulator; run a circuit gate by gate first, then read how those eight numbers get pushed around.

Gates: H(q0) · CNOT(q0→q1)

State |ψ⟩ = 1.00 |000⟩

Three qubits in |000⟩. Apply gates one at a time, or run the whole circuit, then measure.

Plate I A three-qubit statevector, evolved by hand. Pick a circuit, apply its gates one at a time (or run them all), and watch the eight amplitudes as bars: green for phase 0, ochre for phase π. Then Measure to sample an outcome from the squared magnitudes and collapse the state. The Bell and GHZ presets are entangled: their qubits only ever measure in agreement.

The approach

The simulator is a couple of dozen lines with no linear-algebra library, because the structure of the gates makes the matrix multiplication almost disappear. A single-qubit gate is a 2×22\times 2 matrix, and applying it to qubit tt means running that little matrix across every pair of amplitudes whose basis labels differ only in bit tt: the two halves of the state, zipped together. A controlled-NOT is even cheaper, just a swap of the amplitudes in the pairs where the control bit is 1. So the whole engine is: find the pairs, apply the small operation, done. The plate steps through the canonical first circuits and shows the eight amplitudes as bars, height for magnitude and tint for phase, so you can watch the state move gate by gate.

Bars are good for seeing magnitude move, but the state is really a piece of algebra, so I added a written readout underneath them that spells the same eight numbers as an explicit superposition: after the first Hadamard it reads ∣ψ⟩=0.71∣000⟩+0.71∣100⟩|\psi\rangle = 0.71|000\rangle + 0.71|100\rangle, and a phase-flipped branch turns ochre with a minus sign, exactly as its bar does. It updates on every gate, and when I apply one it also prints that gate’s 2×22\times2 matrix (or, for CNOT, what the swap does), so you can watch the matrix on the left produce the new coefficients on the right. That side-by-side is the thing I most wanted the high-level framework to show me and it never did.

Three circuits carry the whole lesson:

  • Superposition. One Hadamard on one qubit splits its amplitude evenly. The qubit is now genuinely both values at once, which the plate shows as two equal bars.
  • The Bell pair. A Hadamard then a CNOT, and the two qubits become entangled: only the outcomes where they agree survive. The state cannot be factored into “qubit 0 is this and qubit 1 is that.” That non-factorability is the whole of entanglement, and it is the resource quantum algorithms actually spend.
  • Phase kickback. Hadamard, then a Z that flips the phase of one branch (shown ochre), then a Hadamard again, and the state lands on a different definite value than it started. The phase was invisible to measurement until the second Hadamard let the branches interfere. Interference on hidden phases is where a quantum algorithm’s speed comes from, and this three-gate circuit is the smallest place you can watch it happen.

The whole engine is a pair loop

What surprised me is how little code that pairing turns into. The eight amplitudes live in two flat arrays, re and im, one for the real parts and one for the imaginary, and a walk over the four pairs is the entire implementation of “apply a unitary to the statevector”:

// Apply a 2x2 gate m to qubit t of an n-qubit state held in re[] / im[].
function apply1(t: number, m: number[][]) {
  const bit = 1 << (N - 1 - t);       // q0 is the HIGH bit of the ket label
  const nre = re.slice(), nim = im.slice();
  for (let i = 0; i < DIM; i++) {
    if (i & bit) continue;            // visit each pair once, from its 0 member
    const j = i | bit;                // the partner: same label, bit t set
    nre[i] = m[0][0] * re[i] + m[0][1] * re[j];
    nre[j] = m[1][0] * re[i] + m[1][1] * re[j];
    // the imaginary parts take the same two lines
  }
  re = nre; im = nim;
}

Four lines of arithmetic, and every gate in the plate is a call to it with a different 2×22\times2:

H=12(111−1),X=(0110),Z=(100−1).H = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix}, \qquad X = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}, \qquad Z = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}.

CNOT does not even need the arithmetic: it is a swap of the two amplitudes in each pair whose control bit is 1, which for three qubits is two swaps and no multiplications at all.

The saving is not cosmetic. Taken literally, a gate on three qubits is an 8×88\times8 matrix times a vector: 64 multiplications, three quarters of them against a zero, since a single-qubit gate leaves only two non-zero entries in each row. The pair loop touches each amplitude once and costs four multiplications per pair, so it scales with 2n2^n and not with 4n4^n. At twenty qubits that is the difference between a million operations and a trillion, and it is the reason a statevector simulator can be written in an afternoon and still be the right algorithm.

One convention is worth stating before you read the bars, because simulators disagree about it and a mismatch is silent. Here qubit 0 is the leftmost bit of the label, so ∣110⟩|110\rangle means q0 = 1, q1 = 1, q2 = 0. Qiskit numbers its wires the other way round, with q0 at the right, so the same circuit reports its outcomes back to front there until you notice.

Entanglement is a determinant you can read off the bars

“You cannot factor it” is the standard definition of entanglement, and standard definitions have a way of staying abstract. With eight numbers in front of you it becomes arithmetic. Suppose the first two qubits were independent, q0 in α∣0⟩+β∣1⟩\alpha|0\rangle + \beta|1\rangle and q1 in γ∣0⟩+δ∣1⟩\gamma|0\rangle + \delta|1\rangle, with q2 left alone. Then the four amplitudes you would read off the plate are forced: ∣000⟩|000\rangle carries αγ\alpha\gamma, ∣010⟩|010\rangle carries αδ\alpha\delta, ∣100⟩|100\rangle carries βγ\beta\gamma, ∣110⟩|110\rangle carries βδ\beta\delta. Multiply the first and the last, multiply the middle two, and the products are the same four factors in a different order. So any product state satisfies

a000 a110−a010 a100=0,a_{000}\,a_{110} - a_{010}\,a_{100} = 0,

which is the determinant of the two-by-two block those four amplitudes make. A state that violates it cannot be written as a q0 state times a q1 state, whatever four numbers you try. Run the Bell preset and read the bars: a000=a110=0.71a_{000} = a_{110} = 0.71 (the plate rounds 1/21/\sqrt{2}) and both middle terms are 0, so the determinant comes to exactly 12\tfrac12 rather than 00. That is not a hint of entanglement, it is a proof, and it takes one subtraction. Run Superposition instead and the same arithmetic gives 0.71×0−0×0.71=00.71 \times 0 - 0 \times 0.71 = 0: one Hadamard on one qubit leaves the three qubits perfectly separable, which is why superposition on its own is not the resource anybody is after.

The same check is what makes measurement so violent. Press Measure and the state becomes a single amplitude of 1 with seven zeros, whose determinant is 0 again. Collapse does not just pick an outcome; it destroys the entanglement on the way, and the plate makes you press Reset to get it back.

Interference, in two numbers

The phase-kickback circuit is three gates long and it carries the entire reason quantum computing buys anything, so here it is by hand. A Hadamard on a pair of amplitudes (a,b)(a, b) returns (a+b2,a−b2)\bigl(\tfrac{a+b}{\sqrt2}, \tfrac{a-b}{\sqrt2}\bigr): a sum and a difference, nothing more.

Start at ∣000⟩|000\rangle, so the q0 pair is (1,0)(1, 0). The first Hadamard makes it (0.71,0.71)(0.71, 0.71). The ZZ flips the sign of the ∣1⟩|1\rangle branch, giving (0.71,−0.71)(0.71, -0.71), and this is the step to watch in the plate, because the two bars do not move at all. Only their tint changes, from green to ochre. Measurement reads squared magnitudes, and (−0.71)2(-0.71)^2 is (0.71)2(0.71)^2, so at this instant the ZZ has done nothing whatsoever that a measurement could detect. Then the second Hadamard takes the sum and the difference of those two numbers: the sum is 00 and the difference is 11. The ∣000⟩|000\rangle branch has cancelled itself out and the ∣100⟩|100\rangle branch is certain.

That cancellation is interference, and at this scale it is a subtraction of two floating-point numbers. A quantum algorithm is an arrangement of gates that makes the wrong answers arrive with signs that cancel and the right one arrive with signs that add, and Grover’s and Shor’s are both that trick at a scale where the number of branches doing the cancelling is astronomical. The three gates here are the smallest honest instance of it, which is why I keep coming back to this preset rather than to the more impressive ones.

Scope, and what next

The simulator is deliberately classical and deliberately tiny: it stores the full 2n2^n statevector, which is exactly the exponential cost that makes classical simulation of quantum computers hopeless past ~40 qubits, and exactly why real quantum hardware would matter. Three qubits is a teaching size, not a useful one. The gates here are all real- valued (H, X, Z, CNOT), so the plate shows phase only as a sign; a fuller version would add the phase gates (S, T) whose amplitudes are genuinely complex, and draw phase as a color wheel rather than two tints. And the lesson of the hackathon itself: the hours went to the high-level framework rather than to reasoning about the state, which is exactly what this rebuild is built to correct. The circuit is the notation. The statevector is the computer.

Keys on this page

A figure's keys are its own: they answer once the figure has focus, so tab to it or click it first. Esc closes this sheet.