Measuring in the X, Y and Z Bases
Measure |+⟩ and |i+⟩ in all three bases by adding basis-change gates before measurement.
For the $X$ basis we add H before measurement, and for the $Y$ basis we add $S^\dagger$ then H. The state $|+\rangle$ is deterministic in $X$ and random in $Y$ and $Z$, and the state $|i+\rangle$ is deterministic in $Y$ and random in $X$ and $Z$. The roughly equal counts in the random lines are identical across lines because the primitive uses the same seed in every call.
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.primitives import StatevectorSampler
def measure_in(basis, prepare):
qc = QuantumCircuit(1)
prepare(qc)
if basis == "x":
qc.h(0)
elif basis == "y":
qc.sdg(0)
qc.h(0)
qc.measure_all()
return qc
states = {"|+>": lambda qc: qc.h(0), "|i+>": lambda qc: (qc.h(0), qc.s(0))}
sampler = StatevectorSampler(seed=9)
for name, prep in states.items():
for basis in ["z", "x", "y"]:
counts = sampler.run([measure_in(basis, prep)], shots=1000).result()[0].data.meas.get_counts()
print(name, basis, dict(sorted(counts.items())))
Line-by-line code explanation
| Line | Explanation |
|---|---|
| 1-2 | Imports. |
| 5 | A function that builds a measurement circuit in a given basis. |
| 6-7 | A one-qubit circuit and state preparation. |
| 8-9 | X basis: Hadamard. |
| 10-12 | Y basis: S† then Hadamard. |
| 13 | Measure in Z after the change of basis. |
| 14 | Return the circuit. |
| 17 | Prepare |+⟩ and prepare |i+⟩ (H then S). |
| 18 | A primitive with seed 9. |
| 19-20 | Each state in each basis. |
| 21 | 1000 shots. |
| 22 | Print. |
Expected output (from an actual run)
|+> z {'0': 503, '1': 497}
|+> x {'0': 1000}
|+> y {'0': 503, '1': 497}
|i+> z {'0': 503, '1': 497}
|i+> x {'0': 503, '1': 497}
|i+> y {'0': 1000}
Counts from StatevectorSampler(seed=9); the deterministic lines do not depend on the seed.
Try it yourself
Related topics
References
- IBM Quantum (2025). Qiskit SDK API documentation. IBM Quantum Documentation quantum.cloud.ibm.com
- 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.
