Quantum Computing Foundations¶
Quantum computing replaces classical binary switches with complex unit vectors that interfere, superpose, and entangle inside exponentially large Hilbert spaces. Building directly on the linear algebra and probability tools from earlier chapters, this section introduces qubits, the Bloch sphere, measurement collapse, tensor products, Bell states, density matrices, and the no-cloning limit.
Why Quantum Computing Begins With Linear Algebra¶
-
If you have ever worried that quantum computing requires years of theoretical physics before a single line of code makes sense, take a deep breath. At its operational core, quantum computing is simply the linear algebra of chapters 01 and 02 upgraded from real vectors to complex unit vectors, paired with the probability rules of chapter 05.
-
Think of a classical bit as a wall light switch. It clicks firmly into
0(off) or1(on), and even if you build a classical probabilistic computer that flips a biased coin, you still only ever add non-negative probabilities between \(0\) and \(1\). A quantum bit, or qubit, behaves much more like a smooth compass needle pointing anywhere on the surface of a globe, carrying both a tilt and an internal wave phase. -
In classical machine learning, every neural network layer multiplies a real feature vector by a weight matrix. In quantum computing and quantum machine learning, every physical operation multiplies a complex state vector by a length-preserving matrix inside a complex inner-product space called a Hilbert space. Master four building blocks (unit vectors, complex phases, inner products, and tensor products) and the apparent mystery of quantum information turns into crisp, intuitive geometry.
The Qubit, Complex Phase, and the Bloch Sphere¶
-
Imagine tossing two pebbles into a still garden pond. Where two wave crests meet, the water rises twice as high (constructive interference). Where a crest meets a trough, the surface flattens completely (destructive interference). Classical probabilities can never cancel one another out because probabilities are never negative, whereas quantum states store complex probability amplitudes whose phases can align to amplify an answer or oppose to erase a wrong one.
-
Physicists write column vectors using Dirac bra-ket notation. The two classical computational basis states \(|0\rangle\) (pronounced "ket zero") and \(|1\rangle\) ("ket one") correspond to the standard orthonormal basis vectors of \(\mathbb{C}^2\).
- A general pure single-qubit state \(|\psi\rangle\) is a superposition of these two basis vectors, weighted by complex amplitudes \(\alpha, \beta \in \mathbb{C}\) whose squared magnitudes sum to one.
-
The conjugate transpose of a ket is a row vector called a bra, written \(\langle \psi | = (\alpha^*, \beta^*)\). Taking the inner product of a bra and a ket gives a complex scalar \(\langle \phi | \psi \rangle = \phi_0^* \psi_0 + \phi_1^* \psi_1\) (the complex generalisation of the dot product from chapter 01). The normalisation constraint \(\langle \psi | \psi \rangle = |\alpha|^2 + |\beta|^2 = 1\) simply says that every valid quantum state is a unit vector.
-
Notice a subtle freedom in complex amplitudes. Multiplying the entire state by a global unit-magnitude phase factor \(e^{i\gamma}\) yields \(e^{i\gamma}|\psi\rangle\), which leaves every measurable probability unchanged because \(|e^{i\gamma}\alpha|^2 = |\alpha|^2\). By contrast, the relative phase \(\phi\) between \(\alpha\) and \(\beta\) is physically crucial because it governs how amplitudes interfere in later gates. Factoring out the unobservable global phase lets us rewrite any pure single-qubit state using just two real angles \(\theta \in [0, \pi]\) and \(\phi \in [0, 2\pi)\).
-
That formula maps every pure qubit state onto a unique point on the surface of a unit sphere in \(\mathbb{R}^3\) known as the Bloch sphere, with Cartesian coordinates \((x, y, z) = (\sin\theta\cos\phi, \; \sin\theta\sin\phi, \; \cos\theta)\).
- The north and south poles (\(\theta = 0\) and \(\theta = \pi\)) represent the classical states \(|0\rangle\) and \(|1\rangle\). Notice that \(|0\rangle\) and \(|1\rangle\) are orthogonal in \(\mathbb{C}^2\) (\(\langle 0 | 1 \rangle = 0\)), yet sit at opposite poles (\(180^\circ\) apart) on the Bloch sphere because of the half-angle \(\theta / 2\).
- The equator (\(\theta = \pi / 2\)) holds equal-magnitude superpositions that differ only in relative phase \(\phi\). Setting \(\phi = 0\) and \(\phi = \pi\) gives the \(X\)-axis states \(|+\rangle = \frac{1}{\sqrt{2}}(|0\rangle + |1\rangle)\) and \(|-\rangle = \frac{1}{\sqrt{2}}(|0\rangle - |1\rangle)\), while \(\phi = \pi/2\) and \(\phi = 3\pi/2\) give the \(Y\)-axis states \(|+i\rangle = \frac{1}{\sqrt{2}}(|0\rangle + i|1\rangle)\) and \(|-i\rangle = \frac{1}{\sqrt{2}}(|0\rangle - i|1\rangle)\).
- Why relative phase matters. Both \(|+\rangle\) and \(|-\rangle\) give a \(50/50\) split if measured immediately in the \(\{|0\rangle, |1\rangle\}\) basis, yet they point in opposite directions along the \(X\) axis. Rotate them through a Hadamard gate and \(|+\rangle\) interferes constructively back into \(|0\rangle\), whereas \(|-\rangle\) interferes constructively into \(|1\rangle\).
-
Working through one quick numerical check makes Dirac notation feel second nature. Take \(|\psi\rangle = \frac{\sqrt{3}}{2}|0\rangle + \frac{i}{2}|1\rangle\). Its squared norm is \(\left|\frac{\sqrt{3}}{2}\right|^2 + \left|\frac{i}{2}\right|^2 = \frac{3}{4} + \frac{1}{4} = 1\), confirming it is a valid unit state. Comparing against the Bloch formula tells us \(\cos(\theta/2) = \sqrt{3}/2\) (so \(\theta = \pi/3\)) and \(e^{i\phi} = i\) (so \(\phi = \pi/2\)), placing \(|\psi\rangle\) in the northern hemisphere above the positive \(Y\) axis.
-
Similarly, computing the inner product between \(|+\rangle\) and \(|-\rangle\) confirms they form a valid rotated orthonormal basis of their own.
The Born Rule and Measurement Collapse¶
-
Imagine spinning a shiny pound coin upright on a wooden desk. While it spins, it behaves like a continuous blend of heads and tails, yet the moment you slap your hand down on it, the motion vanishes and you see one definite classical face. Quantum measurement plays a remarkably similar role, snapping a delicate complex superposition into one concrete classical bit.
-
According to the Born rule, measuring \(|\psi\rangle = \alpha|0\rangle + \beta|1\rangle\) in the computational (\(Z\)) basis yields outcome
0with probability \(P(0) = |\langle 0 | \psi \rangle|^2 = |\alpha|^2\) and outcome1with probability \(P(1) = |\langle 1 | \psi \rangle|^2 = |\beta|^2\). Immediately after observing outcome \(m \in \{0, 1\}\), the state collapses discontinuously to \(|m\rangle\). -
We are never restricted to measuring along the vertical \(Z\) axis alone. We can measure in any orthonormal basis \(\{|u_0\rangle, |u_1\rangle\}\) (such as the horizontal \(X\) basis \(\{|+\rangle, |-\rangle\}\)) by computing the squared overlaps \(|\langle u_0 | \psi \rangle|^2\) and \(|\langle u_1 | \psi \rangle|^2\). In practice, real quantum chips physically read out in the \(Z\) basis, so measuring along \(X\) or \(Y\) simply rotates the qubit into the \(Z\) axis right before readout. This trick is how quantum machine learning circuits make relative phases visible to classical data!
-
Measurement collapse carries two huge practical consequences for quantum machine learning. First, you can never peek directly at the continuous complex numbers \(\alpha\) and \(\beta\) stored inside a single qubit. Second, to estimate the probabilities or the expectation value of a physical observable (represented by a Hermitian matrix \(O = O^\dagger\)), you must prepare the state and measure it repeatedly across \(S\) independent runs called shots.
- For the Pauli \(Z\) observable \(Z = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}\), which assigns eigenvalue \(+1\) to \(|0\rangle\) and \(-1\) to \(|1\rangle\), the expectation value is simply \(\langle Z \rangle = |\alpha|^2 - |\beta|^2 = \cos\theta\), matching the exact \(z\)-coordinate of the qubit on the Bloch sphere. Likewise, \(\langle X \rangle = \sin\theta\cos\phi\) and \(\langle Y \rangle = \sin\theta\sin\phi\), meaning three sets of measurement shots reconstruct the full Bloch vector (a procedure called quantum state tomography).
Multi-Qubit Systems and Tensor Product Spaces¶
-
One qubit alone is easy to simulate on a pocket calculator. The real expressive power of quantum computing arrives when we assemble \(n\) qubits together. To see how their state vectors combine, compare a classical register with a quantum register.
-
If you track two independent classical biased coins, coin A needs \(1\) probability parameter and coin B needs \(1\) parameter, so \(n\) independent coins grow linearly as \(n\) numbers. In quantum mechanics, combining two subsystems uses the tensor product (implemented numerically as the Kronecker product \(\otimes\)). Given \(|\psi_A\rangle = a_0|0\rangle + a_1|1\rangle\) and \(|\psi_B\rangle = b_0|0\rangle + b_1|1\rangle\), their joint state lives in \(\mathbb{C}^2 \otimes \mathbb{C}^2 \cong \mathbb{C}^4\).
-
Every additional qubit doubles the dimensionality of the combined Hilbert space. An \(n\)-qubit register is described by a unit vector in \(\mathbb{C}^{2^n}\) spanning all \(2^n\) binary strings from \(|00\dots 0\rangle\) to \(|11\dots 1\rangle\).
- \(n = 10\) qubits already require \(2^{10} = 1{,}024\) complex amplitudes.
- \(n = 30\) qubits require over one billion complex numbers, filling roughly \(16\,\text{GB}\) of single-precision memory.
- \(n = 50\) qubits require \(2^{50} \approx 1.12 \times 10^{15}\) complex amplitudes, demanding petabytes of classical RAM just to write down a single snapshot of the state vector.
-
Keep a grounded scientific perspective here. An exponentially huge state space does not let you read out \(2^n\) answers simultaneously. When you measure an \(n\)-qubit register, the Born rule collapses the entire \(2^n\)-dimensional wave into one single \(n\)-bit string. The art of quantum algorithms and quantum machine learning is sculpting interference inside that vast space so high-value outcomes emerge with high probability.
Entanglement and Bell States¶
-
Not every vector in \(\mathbb{C}^4\) can be written as a simple product \(|\psi_A\rangle \otimes |\psi_B\rangle\). When a multi-qubit state refuses to factor into independent single-qubit states, the qubits are entangled.
-
Picture placing a left glove and a right glove into two identical sealed boxes and mailing one to London and one to Tokyo. Opening the London box immediately tells you what sits in Tokyo. Classical correlation stops there, because each box already held a fixed glove during transit. Quantum entanglement goes deeper. Neither qubit possesses a definite individual state before measurement, yet their joint wave function locks their outcomes together across every measurement axis, violating classical local-hidden-variable bounds known as Bell inequalities.
-
The four maximally entangled two-qubit states are the famous Bell states, anchored by \(|\Phi^+\rangle\).
-
Let us check algebraically why \(|\Phi^+\rangle\) can never be factored. Suppose there existed single-qubit amplitudes such that \((a_0|0\rangle + a_1|1\rangle) \otimes (b_0|0\rangle + b_1|1\rangle) = \frac{1}{\sqrt{2}}|00\rangle + \frac{1}{\sqrt{2}}|11\rangle\). Matching the four basis coefficients requires \(a_0 b_0 = 1/\sqrt{2}\), \(a_1 b_1 = 1/\sqrt{2}\), \(a_0 b_1 = 0\), and \(a_1 b_0 = 0\). From \(a_0 b_1 = 0\), either \(a_0 = 0\) or \(b_1 = 0\). Yet \(a_0 = 0\) would force \(a_0 b_0 = 0\), and \(b_1 = 0\) would force \(a_1 b_1 = 0\), contradicting the nonzero entries!
-
Thus \(|\Phi^+\rangle\) exists genuinely as a holistic two-qubit object. If you measure qubit A and obtain
0, qubit B instantaneously collapses to0as well, and if A yields1, B yields1, with zero chance of ever observing01or10. In quantum machine learning, entanglement lets a circuit capture complex multi-variable correlations that a product of independent single-qubit models could never represent. -
Remarkably, a matrix tool you already mastered in chapter 02 gives an instant numerical test for two-qubit entanglement! Reshape any two-qubit amplitude vector \((c_{00}, c_{01}, c_{10}, c_{11})^\top\) into a \(2 \times 2\) matrix \(M = \begin{pmatrix} c_{00} & c_{01} \\ c_{10} & c_{11} \end{pmatrix}\) and take its Singular Value Decomposition (SVD), \(M = U \Sigma V^\dagger\) (known in physics as the Schmidt decomposition). A separable product state always produces a rank-\(1\) outer product with a single nonzero singular value \(\sigma_1 = 1\), whereas an entangled state has rank \(2\) (\(\sigma_1, \sigma_2 > 0\)). For \(|\Phi^+\rangle\), \(M = \frac{1}{\sqrt{2}}I\) has two equal singular values \(\sigma_1 = \sigma_2 = 1/\sqrt{2}\), signifying maximal entanglement!
Density Matrices, Mixed States, and the No-Cloning Theorem¶
-
Pure state vectors \(|\psi\rangle\) describe an idealised, perfectly isolated quantum register. Real quantum chips sit inside noisy cryostats where stray heat and electromagnetic fluctuations corrupt amplitudes, and moreover we often wish to inspect just one qubit out of a larger entangled system. Both situations lead to mixed states, which we represent using a density matrix \(\rho\).
-
Think of the difference between a pure state and a mixed state like the difference between a single sharp photograph and a shuffled deck of photographs drawn randomly. If a noisy device prepares pure state \(|\psi_k\rangle\) with classical probability \(p_k\) (\(\sum_k p_k = 1\)), its density matrix is the weighted sum of outer products.
- Comparing two states that both yield \(50\%\)
0and \(50\%\)1in the \(Z\) basis reveals the beauty of density matrices immediately.
-
Both matrices share the exact same diagonal entries (\(1/2, 1/2\)), representing classical basis probabilities. All the quantum magic lives in the off-diagonal entries, known as coherences, which track stable phase relationships between \(|0\rangle\) and \(|1\rangle\). Environmental noise gradually erodes those off-diagonal coherences toward zero, a process called decoherence that turns quantum superpositions back into ordinary classical coin flips!
-
Every valid density matrix is Hermitian (\(\rho = \rho^\dagger\)), positive semidefinite (non-negative eigenvalues), and has unit trace (\(\operatorname{Tr}(\rho) = 1\)). Observable expectations follow the clean trace rule \(\langle O \rangle = \operatorname{Tr}(\rho O)\). Best of all, computing the purity \(\operatorname{Tr}(\rho^2)\) immediately tells us whether a state is pure or mixed.
- Pure states (\(\rho = |\psi\rangle\langle\psi|\)) sit on the outer shell of the Bloch sphere and satisfy \(\operatorname{Tr}(\rho^2) = 1\).
- Mixed states live strictly inside the interior of the Bloch ball and satisfy \(\frac{1}{d} \le \operatorname{Tr}(\rho^2) < 1\) for a \(d\)-dimensional system.
- Reduced density matrices via partial trace. If two qubits share the maximally entangled pure state \(|\Phi^+\rangle\), tracing out qubit B leaves qubit A in the maximally mixed state \(\rho_A = \operatorname{Tr}_B(|\Phi^+\rangle\langle\Phi^+|) = \frac{1}{2}I\) right at the dead centre of the Bloch sphere, with purity \(1/2\) and maximum von Neumann entropy \(S(\rho_A) = -\operatorname{Tr}(\rho_A \log_2 \rho_A) = 1\) bit. Global certainty coexists with complete local ignorance!
-
Finally, quantum linearity imposes a startling engineering constraint called the No-Cloning Theorem (Wootters and Zurek, 1982). On a classical laptop,
y = x.copy()is trivial, and classical backpropagation relies on copying and caching intermediate activation vectors at every layer. On a quantum computer, no unitary operation can clone an arbitrary unknown quantum state. -
The proof takes three lines of linear algebra. Suppose a cloning unitary \(U\) existed such that \(U(|\psi\rangle \otimes |0\rangle) = |\psi\rangle \otimes |\psi\rangle\) for any state \(|\psi\rangle\). Applying \(U\) to two orthogonal states \(|0\rangle\) and \(|1\rangle\) gives \(U|00\rangle = |00\rangle\) and \(U|10\rangle = |11\rangle\). By linearity of matrix multiplication, feeding the superposition \(|+\rangle = \frac{1}{\sqrt{2}}(|0\rangle + |1\rangle)\) must produce
- Yet a true clone of \(|+\rangle\) would be \(|+\rangle \otimes |+\rangle = \frac{1}{2}(|00\rangle + |01\rangle + |10\rangle + |11\rangle)\), which is a completely different vector! The attempted cloner entangled the qubits instead of duplicating them. This single theorem explains why quantum error correction cannot simply use classical triple-copy voting and why variational quantum circuits need specialised gradient rules (section 3) rather than naive backpropagation inside quantum memory.
Take-Home¶
- A single qubit is a complex unit vector \(|\psi\rangle = \alpha|0\rangle + \beta|1\rangle \in \mathbb{C}^2\) with \(|\alpha|^2 + |\beta|^2 = 1\), geometrically visualised on the Bloch sphere via polar angle \(\theta\) and relative phase \(\phi\).
- Complex relative phase drives constructive and destructive interference inside quantum circuits, whereas direct computational-basis measurement collapses \(|\psi\rangle\) to
0or1with Born rule probabilities \(|\alpha|^2\) and \(|\beta|^2\). - Combining \(n\) qubits via tensor products expands the Hilbert space exponentially to \(\mathbb{C}^{2^n}\), yet every measurement still yields only one classical \(n\)-bit string.
- Entangled states such as the Bell state \(|\Phi^+\rangle = \frac{1}{\sqrt{2}}(|00\rangle + |11\rangle)\) cannot be factored into single-qubit states and exhibit maximal local mixedness despite zero global uncertainty.
- Density matrices unify pure states, hardware noise, and entangled subsystems through purity \(\operatorname{Tr}(\rho^2)\), while the no-cloning theorem forbids duplicating unknown quantum states.
Coding Tasks (use CoLab or notebook)¶
-
Sweep a single qubit across polar angles \(\theta \in [0, \pi]\) at fixed azimuthal phase \(\phi = \pi/3\). Compute its Bloch coordinates \((x, y, z)\) and exact Born rule probabilities \(P(0), P(1)\), then simulate \(S = 200\) finite measurement shots per angle to watch sampling noise fluctuate around the exact curve.
import jax import jax.numpy as jnp import matplotlib.pyplot as plt key = jax.random.PRNGKey(42) thetas = jnp.linspace(0.0, jnp.pi, 40) phi = jnp.pi / 3.0 n_shots = 200 alpha = jnp.cos(thetas / 2.0) beta = jnp.exp(1j * phi) * jnp.sin(thetas / 2.0) # Exact Born probabilities and Bloch coordinates p0_exact = jnp.abs(alpha) ** 2 p1_exact = jnp.abs(beta) ** 2 bloch_x = jnp.sin(thetas) * jnp.cos(phi) bloch_y = jnp.sin(thetas) * jnp.sin(phi) bloch_z = jnp.cos(thetas) # Finite-shot Born sampling using uniform draws draws = jax.random.uniform(key, (len(thetas), n_shots)) outcomes_1 = (draws > p0_exact[:, None]).astype(jnp.float32) p1_emp = jnp.mean(outcomes_1, axis=1) z_emp = 1.0 - 2.0 * p1_emp max_norm_err = float(jnp.max(jnp.abs(p0_exact + p1_exact - 1.0))) print(f"Max normalisation error: {max_norm_err:.2e}, Mean |<Z> - Z_emp|: {float(jnp.mean(jnp.abs(bloch_z - z_emp))):.4f}") fig, axes = plt.subplots(1, 2, figsize=(11, 3.8)) axes[0].plot(thetas, p1_exact, color="#3498db", lw=2.2, label="Exact P(1) = sin^2(theta/2)") axes[0].scatter(thetas, p1_emp, color="#e74c3c", s=22, alpha=0.8, label=f"Empirical ({n_shots} shots)") axes[0].set_title("Born Rule Probability vs Finite-Shot Sampling"); axes[0].set_xlabel("Polar angle theta (rad)"); axes[0].set_ylabel("P(1)"); axes[0].legend() axes[1].plot(thetas, bloch_x, color="#27ae60", lw=2.0, label="Bloch x = <X>") axes[1].plot(thetas, bloch_y, color="#9b59b6", lw=2.0, label="Bloch y = <Y>") axes[1].plot(thetas, bloch_z, color="#3498db", lw=2.0, label="Bloch z = <Z>") axes[1].set_title("Bloch Coordinates Along Meridian phi = pi/3"); axes[1].set_xlabel("Polar angle theta (rad)"); axes[1].set_ylabel("Coordinate"); axes[1].legend() plt.tight_layout(); plt.show() -
Explore the transition from a separable product state to a maximally entangled Bell state using the two-qubit family \(|\psi(\gamma)\rangle = \cos\gamma|00\rangle + \sin\gamma|11\rangle\). Compute the full density matrix \(\rho\), partial-trace out qubit B to obtain \(\rho_A\), and plot both subsystem purity \(\operatorname{Tr}(\rho_A^2)\) and von Neumann entanglement entropy \(S(\rho_A)\) across \(\gamma \in [0, \pi/2]\).
import jax.numpy as jnp import matplotlib.pyplot as plt gammas = jnp.linspace(0.0, jnp.pi / 2.0, 100) purities, entropies = [], [] for g in gammas: psi = jnp.array([jnp.cos(g), 0.0, 0.0, jnp.sin(g)], dtype=jnp.complex64) rho = jnp.outer(psi, jnp.conj(psi)) # Reshape 4x4 density matrix into (A_row, B_row, A_col, B_col) and trace over B rho_4d = rho.reshape(2, 2, 2, 2) rho_a = jnp.einsum("abcb->ac", rho_4d) purity = float(jnp.real(jnp.trace(jnp.dot(rho_a, rho_a)))) evals = jnp.clip(jnp.real(jnp.linalg.eigvalsh(rho_a)), 1e-12, 1.0) entropy = float(-jnp.sum(evals * jnp.log2(evals))) purities.append(purity) entropies.append(entropy) bell_idx = len(gammas) // 2 print(f"At gamma=0 (separable) -> Purity: {purities[0]:.3f}, Entropy: {entropies[0]:.3f} bits") print(f"At gamma=pi/4 (Bell) -> Purity: {purities[bell_idx]:.3f}, Entropy: {entropies[bell_idx]:.3f} bits") fig, axes = plt.subplots(1, 2, figsize=(11, 3.8)) axes[0].plot(gammas, purities, color="#9b59b6", lw=2.3) axes[0].axvline(jnp.pi / 4.0, color="#e74c3c", ls="--", lw=1.2, label="Bell state (pi/4)") axes[0].set_title("Reduced Subsystem Purity Tr(rho_A^2)"); axes[0].set_xlabel("Entangling angle gamma (rad)"); axes[0].set_ylabel("Purity"); axes[0].legend() axes[1].plot(gammas, entropies, color="#27ae60", lw=2.3) axes[1].axvline(jnp.pi / 4.0, color="#e74c3c", ls="--", lw=1.2, label="Max entanglement (1 bit)") axes[1].set_title("Von Neumann Entanglement Entropy S(rho_A)"); axes[1].set_xlabel("Entangling angle gamma (rad)"); axes[1].set_ylabel("Entropy (bits)"); axes[1].legend() plt.tight_layout(); plt.show() -
Demonstrate quantum interference versus classical probability. Start a qubit in \(|0\rangle\), apply a Hadamard split \(H\), imprint a tunable relative phase \(\phi \in [0, 2\pi]\) on the \(|1\rangle\) branch via \(P(\phi) = \text{diag}(1, e^{i\phi})\), and recombine with a second Hadamard \(H\). Watch the probability of returning to \(|0\rangle\) oscillate smoothly from \(1\) (constructive) down to \(0\) (destructive), whereas two classical \(50/50\) coin flips would stay flat at \(0.5\).
import jax.numpy as jnp import matplotlib.pyplot as plt H = jnp.array([[1.0, 1.0], [1.0, -1.0]], dtype=jnp.complex64) / jnp.sqrt(2.0) ket0 = jnp.array([1.0, 0.0], dtype=jnp.complex64) phis = jnp.linspace(0.0, 2.0 * jnp.pi, 160) p0_quantum, p1_quantum = [], [] for phi in phis: phase_gate = jnp.array([[1.0, 0.0], [0.0, jnp.exp(1j * phi)]], dtype=jnp.complex64) state = jnp.dot(H, jnp.dot(phase_gate, jnp.dot(H, ket0))) p0_quantum.append(float(jnp.abs(state[0]) ** 2)) p1_quantum.append(float(jnp.abs(state[1]) ** 2)) p0_quantum = jnp.array(p0_quantum) p1_quantum = jnp.array(p1_quantum) classical_flat = jnp.full_like(phis, 0.5) print(f"phi=0 -> P(0)={float(p0_quantum[0]):.3f}, P(1)={float(p1_quantum[0]):.3f} (constructive on |0>)") print(f"phi=pi -> P(0)={float(p0_quantum[80]):.3f}, P(1)={float(p1_quantum[80]):.3f} (destructive on |0>)") plt.figure(figsize=(7.5, 4.0)) plt.plot(phis, p0_quantum, color="#3498db", lw=2.4, label="Quantum P(0) = cos^2(phi/2)") plt.plot(phis, p1_quantum, color="#e74c3c", lw=2.2, ls="-.", label="Quantum P(1) = sin^2(phi/2)") plt.plot(phis, classical_flat, color="#666", lw=1.6, ls="--", label="Classical 50/50 baseline") plt.title("Constructive and Destructive Quantum Interference Across Relative Phase") plt.xlabel("Relative phase phi (rad)"); plt.ylabel("Measurement probability") plt.legend(); plt.tight_layout(); plt.show()