The Swap Test
Estimate |⟨a|b⟩|² from the ancilla's measurement probability, 2P(0) − 1: 0.4196 vs the exact 0.4179.
The test uses a CSWAP (Fredkin) gate between two Hadamards on an ancilla qubit, so $P(0)=(1+|\langle a|b\rangle|^2)/2$. The statistical error of the estimate from 20000 shots is about $2\sqrt{P(0)(1-P(0))/N}\approx0.0064$, and the observed difference of 0.0017 is within it. The two states match the lab's swap-test experiment.
Requirements: pip install qiskit qiskit-aer. The code runs on your machine or in Colab, not inside WordPress.
Code
from qiskit import QuantumCircuit
from qiskit.quantum_info import Statevector
from qiskit.primitives import StatevectorSampler
def prep(theta, phi):
qc = QuantumCircuit(1)
qc.ry(theta, 0)
qc.rz(phi, 0)
return qc
a, b = prep(0.4, 0.2), prep(1.9, -1.0)
qc = QuantumCircuit(3, 1)
qc.compose(a, [1], inplace=True)
qc.compose(b, [2], inplace=True)
qc.h(0)
qc.cswap(0, 1, 2)
qc.h(0)
qc.measure(0, 0)
shots = 20000
counts = StatevectorSampler(seed=2).run([qc], shots=shots).result()[0].data.c.get_counts()
p0 = counts.get("0", 0) / shots
exact = abs(Statevector(a).inner(Statevector(b))) ** 2
print("P(0) =", p0)
print("estimated |<a|b>|^2 = 2 P(0) - 1 =", round(2 * p0 - 1, 4))
print("exact |<a|b>|^2 =", round(float(exact), 4))
Line-by-line code explanation
| Line | Explanation |
|---|---|
| 1-3 | Imports. |
| 6-10 | A function that prepares the state RZ(φ)RY(θ)|0⟩. |
| 13 | The two states a and b. |
| 14 | Three qubits: ancilla, a and b. |
| 15-16 | Place the two states on q1 and q2. |
| 17 | Hadamard on the ancilla. |
| 18 | Controlled swap. |
| 19 | A second Hadamard. |
| 20 | Measure the ancilla. |
| 22-23 | 20000 shots with seed 2. |
| 24 | Estimate P(0). |
| 25 | The exact value from the two state vectors. |
| 26-28 | Print the estimate and the exact value. |
Expected output (from an actual run)
P(0) = 0.7098 estimated |<a|b>|^2 = 2 P(0) - 1 = 0.4196 exact |<a|b>|^2 = 0.4179
Counts from StatevectorSampler(seed=2); the exact value is deterministic.
Try it yourself
Related topics
References
- Michael A. Nielsen; Isaac L. Chuang (2010). Quantum Computation and Quantum Information (10th Anniversary Edition). Cambridge University Press doi:10.1017/CBO9780511976667The standard reference for quantum computing; the Crossref record gives 2012 for the Cambridge Core online edition.
- IBM Quantum (2025). Qiskit SDK API documentation. IBM Quantum Documentation quantum.cloud.ibm.com
