Quantum Gates, Circuits, and Algorithms¶
Quantum gates evolve qubit registers through reversible unitary transformations that rotate state vectors and weave entanglement across wires. This section builds the standard single- and two-qubit gate toolkit, explains how to read quantum circuit diagrams, and reveals how landmark algorithms turn wave interference into genuine speedups.
Quantum Gates as Reversible Unitary Matrices¶
-
Think about a classical digital
ANDgate. If I tell you the output bit is0, can you tell whether the two input bits were00,01, or10? No, because the classical gate irreversibly erased information as heat. Quantum mechanics forbids such erasure inside an isolated register. Every quantum gate behaves like turning a flawless crystal prism in midair, redirecting light without ever losing a single photon, so you can always run the motion backwards to recover the exact starting state. -
Mathematically, every \(n\)-qubit quantum gate is a \(2^n \times 2^n\) unitary matrix \(U\), the complex counterpart of the orthogonal rotation matrices we studied in chapter 02.
- Here \(U^\dagger\) is the conjugate transpose of \(U\). Unitarity guarantees two vital physical properties at once. First, every gate preserves vector length (\(\|U|\psi\rangle\|^2 = \langle \psi | U^\dagger U | \psi \rangle = \langle \psi | \psi \rangle = 1\)), ensuring probabilities always sum cleanly to one. Second, every gate is strictly reversible, because applying \(U^\dagger\) undoes \(U\) without a trace.
Single-Qubit Gates and Parametric Rotations¶
-
On the Bloch sphere from section 1, every single-qubit unitary gate corresponds to a rigid 3D rotation around some axis (up to an unobservable global phase). Imagine gripping the sphere by one of its three axes and twisting either by a sharp \(180^\circ\) flip or by a smooth continuous angle \(\theta\).
-
Four fixed single-qubit gates appear in nearly every quantum circuit.
- Pauli-\(X\) (bit flip). Rotates the Bloch sphere by \(\pi\) radians around the \(X\) axis, swapping \(|0\rangle \leftrightarrow |1\rangle\) just like a classical
NOTgate. - Pauli-\(Y\) (bit and phase flip). Rotates by \(\pi\) radians around the \(Y\) axis, swapping basis states while injecting an imaginary phase factor \(\pm i\).
- Pauli-\(Z\) (phase flip). Rotates by \(\pi\) radians around the \(Z\) axis, leaving \(|0\rangle\) untouched while flipping the sign of \(|1\rangle\) to \(-|1\rangle\).
- Hadamard (\(H\)). Rotates by \(\pi\) around the diagonal axis halfway between \(X\) and \(Z\), mapping \(|0\rangle \to |+\rangle = \frac{1}{\sqrt{2}}(|0\rangle + |1\rangle)\) and \(|1\rangle \to |-\rangle = \frac{1}{\sqrt{2}}(|0\rangle - |1\rangle)\). Applying \(H\) to all \(n\) qubits starting in \(|0\dots 0\rangle\) creates an equal superposition over all \(2^n\) bitstrings in a single parallel step!
- Pauli-\(X\) (bit flip). Rotates the Bloch sphere by \(\pi\) radians around the \(X\) axis, swapping \(|0\rangle \leftrightarrow |1\rangle\) just like a classical
- Fixed gates alone are like rigid wooden gears. For quantum machine learning, we need continuous knobs that an optimiser can tune smoothly, just like neural network weights. Exponentiating the Pauli matrices yields the parametric rotation gates \(R_x(\theta)\), \(R_y(\theta)\), and \(R_z(\theta)\), which rotate a qubit by angle \(\theta\) around the \(X\), \(Y\), or \(Z\) axis of the Bloch sphere.
-
Notice how cleanly these matrices behave when you multiply them out. Applying Hadamard twice gives \(H^2 = \frac{1}{2}\begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix}\begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix} = \begin{pmatrix} 1 & 0 \\ 0 & 1 \end{pmatrix} = I\), proving \(H\) is its own inverse. Even more neatly, sandwiching Pauli-\(X\) between two Hadamards converts a bit flip into a phase flip (\(H X H = Z\)) and vice versa (\(H Z H = X\)), because Hadamard swaps the \(X\) and \(Z\) axes on the Bloch sphere.
-
Any arbitrary single-qubit unitary can be decomposed into at most three Euler rotations (such as \(R_z(\alpha) R_y(\beta) R_z(\gamma)\)), meaning three real angles suffice to steer a qubit from any point on the Bloch sphere to any other.
Two-Qubit Entangling Gates and Universal Gate Sets¶
-
If a circuit contained only single-qubit rotations, each qubit would spin inside its own private Bloch sphere forever, and the full \(n\)-qubit state would stay trapped as a trivially simulable separable product. To unlock entanglement, qubits must conditionally interact.
-
Picture two ballroom dancers holding hands where the second dancer performs a spin only when the first dancer raises an arm. That conditional coupling is the Controlled-NOT (
CNOT) gate. It takes a control qubit and a target qubit, leaving the target untouched when the control is \(|0\rangle\) and applying Pauli-\(X\) to flip the target when the control is \(|1\rangle\). Its sibling, the Controlled-\(Z\) (CZ) gate, applies a phase flip \(-1\) only to the \(|11\rangle\) basis component, making it beautifully symmetric between the two qubits (and related directly by \(H\) on the target wire, \(\text{CNOT} = (I \otimes H)\,\text{CZ}\,(I \otimes H)\)).
-
Watch the exact \(4 \times 4\) matrix arithmetic that turns \(|00\rangle\) into the maximally entangled Bell state \(|\Phi^+\rangle\) from section 1. First, applying \(H\) to qubit \(0\) while doing nothing (\(I\)) to qubit \(1\) forms the Kronecker product \(H \otimes I\), sending \((1, 0, 0, 0)^\top\) to \(\frac{1}{\sqrt{2}}(1, 0, 1, 0)^\top = \frac{1}{\sqrt{2}}(|00\rangle + |10\rangle)\). Next, multiplying by
CNOTswaps the third and fourth entries (|10>and|11>), delivering \(\frac{1}{\sqrt{2}}(1, 0, 0, 1)^\top = \frac{1}{\sqrt{2}}(|00\rangle + |11\rangle)\)! -
Remarkably, just as classical
NANDgates can build any digital microprocessor, combining arbitrary single-qubit rotations (\(R_x, R_y, R_z\)) with a single two-qubit entangling gate (CNOTorCZ) forms a universal gate set. Any unitary matrix on \(n\) qubits can be expressed as a sequence of gates from this tiny alphabet. For fault-tolerant digital quantum chips, the discrete Clifford+\(T\) set (\(\{H, S, T, \text{CNOT}\}\), where \(T = \text{diag}(1, e^{i\pi/4})\)) approximates any unitary to arbitrary precision \(\epsilon\) with only polylogarithmic overhead via the Solovay-Kitaev theorem.
Reading Quantum Circuit Diagrams Left-to-Right¶
- A quantum circuit diagram reads exactly like a musical staff for an orchestra. Each horizontal wire represents one qubit evolving forward in time from left to right, rectangular boxes represent single-qubit gates, vertical lines linking a solid dot to a target symbol (
⊕forCNOT, or another dot forCZ) represent entangling gates, and meter boxes at the right end represent measurement collapsing quantum wires into double-line classical bits.
-
Watch out for one famous notational trap that trips up almost every newcomer at first. Circuit diagrams flow left to right in time, whereas matrix multiplication acts right to left on a column vector! If qubit \(0\) passes through gate \(A\) first and gate \(B\) second, the combined mathematical operator is \(U = B A\), because \(B\) multiplies the output of \(A|\psi\rangle\). Similarly, gates stacked vertically on separate wires at the same time slice combine via the tensor product \(A \otimes B\).
-
When evaluating whether a circuit can actually run on real hardware, engineers track two headline metrics analogous to memory footprint and latency in GPU programming (chapter 19). Circuit width is the number of qubits (horizontal wires), while circuit depth is the number of sequential time slices from left to right. Because real two-qubit entangling gates suffer roughly ten times higher error rates than single-qubit rotations and qubits only stay coherent for microseconds, minimising two-qubit gate depth is one of the highest-leverage skills in quantum software engineering.
Turning Interference Into Algorithmic Speedup¶
-
Pop-science articles often claim that a quantum computer solves hard problems by "trying all \(2^n\) answers simultaneously in parallel universes". That slogan is misleading. Preparing a uniform superposition over \(2^n\) candidates is easy, yet if you measure immediately you simply pull out one uniformly random guess, no better than rolling dice!
-
Every genuine quantum speedup relies on choreographed interference. A quantum algorithm uses phase flips and rotations to make the complex amplitudes of wrong paths cancel destructively while making the amplitudes of the true answer reinforce constructively. Four classic algorithms illustrate the core patterns behind quantum advantage.
Deutsch-Jozsa Intuition¶
-
Suppose a friend hands you a sealed black-box function \(f(x) \in \{0, 1\}\) taking \(n\)-bit inputs, and promises that \(f\) is either constant (outputs the same bit for every input) or balanced (outputs
0on half the inputs and1on the other half). Classically, in the worst case you must test \(2^{n-1} + 1\) inputs before being completely certain. -
Imagine testing whether a hidden balance scale has identical weights on both pans or opposing weights without checking every stone individually. The Deutsch-Jozsa algorithm places all \(n\) input qubits into uniform superposition with \(H^{\otimes n}\), evaluates the oracle once using a phase kickback trick that encodes \(f(x)\) into the sign \((-1)^{f(x)}\) of each basis amplitude, and applies a final \(H^{\otimes n}\). If \(f\) is constant, every branch carries the same sign and interferes constructively back into \(|0\dots 0\rangle\) with probability \(1\). If \(f\) is balanced, equal numbers of \(+1\) and \(-1\) signs cancel destructively on \(|0\dots 0\rangle\), giving probability \(0\)! One single query decides the global property with certainty.
Grover's Amplitude Amplification¶
-
Now consider searching a completely unstructured database of \(N = 2^n\) items to find one marked target \(|w\rangle\), like hunting for one specific key inside a bucket of \(N\) identical unlabelled keys. Classically, you must try on average \(N/2\) keys (\(O(N)\) queries).
-
Grover's algorithm finds the target in only \(O(\sqrt{N})\) queries by repeating a two-step Grover iterate \(G = D O_w\) that performs pure 2D geometric rotation! Starting from the uniform superposition \(|s\rangle = H^{\otimes n}|0\dots 0\rangle\), the state vector sits inside the two-dimensional plane spanned by the target \(|w\rangle\) and the uniform superposition of all non-target items \(|s_\perp\rangle\), tilted at a tiny initial angle \(\theta = \arcsin(1/\sqrt{N})\).
- Step 1, Oracle phase flip (\(O_w = I - 2|w\rangle\langle w|\)). Leaves every non-target amplitude unchanged and flips the sign of the target amplitude from \(+1/\sqrt{N}\) to \(-1/\sqrt{N}\). Geometrically, this reflects the state vector across the horizontal axis \(|s_\perp\rangle\), dragging the average amplitude slightly downward.
- Step 2, Diffusion or inversion about the mean (\(D = 2|s\rangle\langle s| - I\)). Reflects every amplitude across the new mean (equivalently reflecting the state vector across \(|s\rangle\)). Because the marked item sat far below the mean, flipping it across the mean catapults its amplitude skyward while pulling all non-target amplitudes closer to zero!
-
A tiny \(n = 2\) (\(N = 4\)) example makes the magic unmistakable. Start with equal amplitudes \(\bigl(\frac{1}{2}, \frac{1}{2}, \frac{1}{2}, \frac{1}{2}\bigr)\) and suppose the third item is the target. The oracle flips its sign to \(\bigl(\frac{1}{2}, \frac{1}{2}, -\frac{1}{2}, \frac{1}{2}\bigr)\), lowering the mean from \(0.5\) to \(0.25\). Now invert every amplitude \(a_j\) about the mean \(\mu = 0.25\) via \(a_j \mapsto 2\mu - a_j = 0.5 - a_j\). Every non-target amplitude collapses to \(0.5 - 0.5 = 0\), while the marked amplitude rockets to \(0.5 - (-0.5) = 1\)! In one single oracle call (versus up to three classical checks), Grover finds the target with \(100\%\) certainty.
-
A classic geometry fact states that two consecutive reflections equal a rotation by twice the angle between the mirror lines. Each Grover iteration therefore rotates the state vector steadily closer to \(|w\rangle\) by \(+2\theta\). After \(k\) iterations, the success probability is \(\sin^2\bigl((2k+1)\theta\bigr)\), peaking near unity at \(k^\star \approx \lfloor \frac{\pi}{4}\sqrt{N} \rfloor\). Crucially, Grover search is periodic. Keep iterating past \(k^\star\) and you over-rotate right past the target, watching the success probability fall back down!
The Quantum Fourier Transform¶
- In chapter 09, we saw how the Fast Fourier Transform (FFT) decomposes a classical signal of length \(N\) into its hidden periodic frequencies in \(O(N \log N)\) operations. The Quantum Fourier Transform (QFT) applies the exact same unitary Fourier matrix to the \(N = 2^n\) complex amplitudes of an \(n\)-qubit register.
-
Astonishingly, because the QFT exploits the recursive butterfly factorisation of the FFT directly inside quantum wires, a quantum circuit implements the exact QFT on \(n\) qubits using only \(O(n^2)\) gates (a tidy ladder of Hadamards and controlled phase rotations, plus bit-reversal swaps), compared with \(O(n 2^n)\) classical operations!
-
Here again, precision matters. You cannot use QFT to replace classical audio FFTs and print out all \(2^n\) frequency bins, because measurement collapses the spectrum to a single frequency index. Instead, QFT shines as a hidden subroutine inside Quantum Phase Estimation (QPE) and Shor's integer factoring algorithm, where extracting just one dominant period or eigenvalue unlocks exponential speedups.
HHL Intuition for Linear Systems¶
-
Solving a huge linear system \(A\mathbf{x} = \mathbf{b}\) sits at the heart of least-squares regression, kernel methods, and Gaussian processes (chapters 02 and 06). Classical direct solvers scale polynomially in dimension \(N\), while the Harrow-Hassidim-Lloyd (HHL) algorithm prepares a quantum state \(|x\rangle \propto A^{-1}|b\rangle\) in time scaling logarithmically as \(O(\log N \cdot s^2 \kappa^2 / \epsilon)\) for an \(s\)-sparse Hermitian matrix \(A\) with condition number \(\kappa\).
-
The intuition stitches together every tool we have built so far. First, Quantum Phase Estimation decomposes \(|b\rangle\) into the eigenvectors \(|u_j\rangle\) of \(A\) and writes each eigenvalue \(\lambda_j\) into an auxiliary register. Second, a controlled rotation tilts an ancilla qubit by an angle proportional to \(1/\lambda_j\), effectively dividing each eigen-amplitude by \(\lambda_j\). Third, uncomputing the phase register and post-selecting on the ancilla yields \(|x\rangle \propto \sum_j (\beta_j / \lambda_j)|u_j\rangle\).
-
HHL sparked the entire first wave of quantum machine learning research, yet it comes with four vital real-world caveats (famously catalogued by Scott Aaronson). Loading an arbitrary dense classical vector \(\mathbf{b}\) into \(|b\rangle\) can destroy the logarithmic speedup, matrix \(A\) must be sparse and well-conditioned (\(\kappa\) small), deep phase estimation requires fault-tolerant error-corrected qubits we do not yet possess, and at the end you can only read out summary expectation values \(\langle x | M | x \rangle\) rather than every entry of \(\mathbf{x}\). Those practical realities motivate the near-term variational circuits we explore next in section 3.
Take-Home¶
- Every quantum gate is a reversible unitary matrix (\(U^\dagger U = I\)) that preserves total probability norm and rotates quantum state vectors inside Hilbert space without losing information.
- Fixed Pauli gates (\(X, Y, Z\)) and Hadamard (\(H\)) handle bit flips, phase flips, and uniform superpositions, while parametric rotations (\(R_x, R_y, R_z\)) act as continuous tunable parameters.
- Combining single-qubit rotations with a two-qubit entangling gate (
CNOTorCZ) forms a universal gate set capable of representing any \(n\)-qubit unitary, read left-to-right in circuit diagrams and applied right-to-left in matrix algebra. - Quantum speedups stem from choreographed interference rather than naive parallel readout, exemplified by Deutsch-Jozsa phase kickback and Grover's \(O(\sqrt{N})\) geometric amplitude amplification.
- The Quantum Fourier Transform implements Fourier interference on \(2^n\) amplitudes in \(O(n^2)\) gates, powering phase estimation and linear-system algorithms like HHL subject to realistic data-loading and readout limits.
Coding Tasks (use CoLab or notebook)¶
-
Build a clean two-qubit quantum circuit simulator from scratch in JAX. Implement
H,X,Y,Z,Ry,Rz,CNOT, andCZ, verify unitarity \(U^\dagger U = I\), prepare all four Bell states from computational basis inputs, and visualise their basis probabilities and amplitudes.import jax.numpy as jnp import matplotlib.pyplot as plt I2 = jnp.eye(2, dtype=jnp.complex64) X = jnp.array([[0, 1], [1, 0]], dtype=jnp.complex64) Z = jnp.array([[1, 0], [0, -1]], dtype=jnp.complex64) H = jnp.array([[1, 1], [1, -1]], dtype=jnp.complex64) / jnp.sqrt(2.0) CNOT = jnp.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], dtype=jnp.complex64) def ry(theta): c, s = jnp.cos(theta / 2.0), jnp.sin(theta / 2.0) return jnp.array([[c, -s], [s, c]], dtype=jnp.complex64) # Verify unitarity of a composed circuit U = CNOT @ (H x I) @ (Ry x I) U_bell = jnp.dot(CNOT, jnp.kron(H, I2)) U_test = jnp.dot(U_bell, jnp.kron(ry(0.7), I2)) unitarity_err = float(jnp.max(jnp.abs(jnp.dot(jnp.conj(U_test.T), U_test) - jnp.eye(4)))) print(f"Max unitarity error ||U^dagger U - I||: {unitarity_err:.2e}") basis_labels = ["|00>", "|01>", "|10>", "|11>"] bell_names = ["|Phi+>", "|Psi+>", "|Phi->", "|Psi->"] bell_states = [jnp.dot(U_bell, jnp.eye(4, dtype=jnp.complex64)[k]) for k in range(4)] for name, st in zip(bell_names, bell_states): amps = [f"{float(jnp.real(a)):+.2f}" for a in st] print(f"{name} amplitudes -> {amps}") fig, axes = plt.subplots(1, 4, figsize=(11.5, 3.2), sharey=True) colors = ["#3498db", "#27ae60", "#9b59b6", "#e74c3c"] for ax, name, st, col in zip(axes, bell_names, bell_states, colors): ax.bar(basis_labels, jnp.real(st), color=col, width=0.55) ax.axhline(0.0, color="#333", lw=0.9); ax.set_ylim(-0.9, 0.9) ax.set_title(name); ax.set_ylabel("Amplitude" if name == "|Phi+>" else "") plt.suptitle("Real Amplitudes of All Four Entangled Bell States") plt.tight_layout(); plt.show() -
Simulate Grover's amplitude amplification on \(n = 5\) qubits (\(N = 32\) items, target index \(w = 19\)). Track the target measurement probability across \(k = 0 \dots 12\) iterations to observe both the rapid quadratic boost to the peak near \(k^\star = \lfloor \frac{\pi}{4}\sqrt{32} \rfloor = 4\) and the periodic drop caused by over-rotation.
import jax.numpy as jnp import matplotlib.pyplot as plt n_qubits = 5 N = 2 ** n_qubits target = 19 # Initial uniform superposition |s> s_vec = jnp.ones(N, dtype=jnp.float32) / jnp.sqrt(float(N)) oracle_signs = jnp.where(jnp.arange(N) == target, -1.0, 1.0) state = s_vec probs_target, steps = [float(state[target] ** 2)], [0] amp_snapshots = {0: state} for k in range(1, 13): # Step 1: Oracle phase flip on target item state = state * oracle_signs # Step 2: Diffusion (inversion about the mean) state = 2.0 * jnp.mean(state) - state probs_target.append(float(state[target] ** 2)) steps.append(k) if k in (1, 4): amp_snapshots[k] = state opt_k = int(jnp.argmax(jnp.array(probs_target))) print(f"Optimal step k*={opt_k} (theory ~{0.25 * float(jnp.pi) * float(jnp.sqrt(N)):.2f}), peak P(target)={probs_target[opt_k]:.4f}") fig, axes = plt.subplots(1, 2, figsize=(11, 3.8)) axes[0].plot(steps, probs_target, "o-", color="#27ae60", lw=2.2) axes[0].axvline(opt_k, color="#e74c3c", ls="--", lw=1.2, label=f"Peak at k={opt_k}") axes[0].set_title("Grover Target Probability vs Iterations (N=32)"); axes[0].set_xlabel("Grover iterations k"); axes[0].set_ylabel("P(target)"); axes[0].legend() bar_cols = ["#e74c3c" if idx == target else "#3498db" for idx in range(N)] axes[1].bar(jnp.arange(N), amp_snapshots[4], color=bar_cols, width=0.75) axes[1].axhline(0.0, color="#333", lw=0.8) axes[1].set_title(f"Amplitudes After k=4 Steps (Target {target} Highlighted)"); axes[1].set_xlabel("Basis index"); axes[1].set_ylabel("Amplitude") plt.tight_layout(); plt.show() -
Construct the exact \(n = 4\) qubit (\(N = 16\)) Quantum Fourier Transform unitary matrix \(F_{jk} = \frac{1}{\sqrt{N}} e^{2\pi i j k / N}\), verify that it matches the inverse-normalised classical
jnp.fft.ifftto machine precision, and watch it transform a periodic quantum state with hidden period \(r = 4\) into sharp frequency peaks!import jax.numpy as jnp import matplotlib.pyplot as plt n_qubits = 4 N = 2 ** n_qubits idx = jnp.arange(N) # Build exact QFT unitary matrix QFT = jnp.exp(2j * jnp.pi * jnp.outer(idx, idx) / N) / jnp.sqrt(float(N)) unitary_err = float(jnp.max(jnp.abs(jnp.dot(jnp.conj(QFT.T), QFT) - jnp.eye(N)))) # Prepare a periodic quantum state |psi> = (|1> + |5> + |9> + |13>) / 2 (period r = 4) mask = ((idx - 1) % 4 == 0).astype(jnp.float32) psi_periodic = (mask / jnp.sqrt(jnp.sum(mask))).astype(jnp.complex64) psi_freq = jnp.dot(QFT, psi_periodic) fft_ref = jnp.fft.ifft(psi_periodic) * jnp.sqrt(float(N)) fft_diff = float(jnp.max(jnp.abs(psi_freq - fft_ref))) print(f"QFT unitarity error: {unitary_err:.2e}, Max diff vs classical IFFT: {fft_diff:.2e}") fig, axes = plt.subplots(1, 2, figsize=(11, 3.8)) axes[0].bar(idx, jnp.abs(psi_periodic) ** 2, color="#3498db", width=0.65) axes[0].set_title("Input Periodic State (Period r = 4)"); axes[0].set_xlabel("Computational basis |x>"); axes[0].set_ylabel("Probability") axes[1].bar(idx, jnp.abs(psi_freq) ** 2, color="#9b59b6", width=0.65) axes[1].set_title("Output After QFT (Sharp Peaks at Multiples of N/r = 4)"); axes[1].set_xlabel("Frequency basis |k>"); axes[1].set_ylabel("Probability") plt.tight_layout(); plt.show()