Skip to main content

View on GitHub

Open this notebook in GitHub to run it yourself
The swap test is a quantum function that checks the overlap between two quantum states. The inputs of the function are two quantum registers of the same size, ∣ψ1⟩, ∣ψ2⟩|\psi_1\rangle, \,|\psi_2\rangle, and it returns as output a single test qubit whose state encodes the overlap between the two inputs: ∣q⟩test=α∣0⟩+1−α2∣1⟩|q\rangle_{\rm test} = \alpha|0\rangle + \sqrt{1-\alpha^2}|1\rangle, with α2=12(1+∣⟨ψ1∣ψ2⟩∣2).\alpha^2 = \frac{1}{2}\left(1+|\langle \psi_1 |\psi_2 \rangle |^2\right). Thus, the probability of measuring the test qubit at state ∣0⟩|0\rangle is 11 if the states are identical (up to a global phase) and 0.5 if the states are orthogonal to each other. The quantum model starts with an HH gate on the test qubit, followed by swapping between the two states controlled on the test qubit (a controlled-SWAP gate for each of the qubits in the two states) and a final HH gate on the test qubit. A general scheme of the swap test algorithm: Prepare two random states:
Create a model and synthesize:
Output:

Swap Test Qmod Implementations

The swap test is defined as a library function in the Qmod language. Verify the results:
Output:

Comparing Measured with Exact Overlap

Using the expected probability of measuring the state ∣0⟩|0\rangle as defined above, α2=12(1+∣⟨ψ1∣ψ2⟩∣2),\alpha^2 = \frac{1}{2}\left(1+|\langle \psi_1 |\psi_2 \rangle |^2\right), we extract the overlap ∣⟨ψ1∣ψ2⟩∣=2P(qtest=∣0⟩)−1|\langle \psi_1 |\psi_2 \rangle |=\sqrt{2 P\left(q_{\text{test}}=|0\rangle\right)-1}. The exact overlap is computed with the dot product of the two state vectors. Note that for the sake of this demonstration we execute this circuit 100,000100,000 times to improve the precision of the probability estimate. This is usually not required in actual programs.
Output: