Operators and Unitarity Checks
Compute a circuit's matrix with Operator, and verify HXH = Z, CNOT unitarity and that three CNOTs equal SWAP.
The Operator class computes the unitary matrix of a circuit without measurement. equiv compares two operators up to global phase, and is_unitary checks $U^\dagger U=I$.
Watch the ordering: the printed CNOT matrix is in Qiskit's little-endian order (the control $q_0$ is the least significant bit), so it swaps indices 1 and 3, whereas the textbook matrix (control is the first, most significant qubit) swaps indices 2 and 3.
Requirements: pip install qiskit numpy. The code runs on your machine or in Colab, not inside WordPress.
Code
import numpy as np
from qiskit import QuantumCircuit
from qiskit.quantum_info import Operator
hxh = QuantumCircuit(1)
hxh.h(0)
hxh.x(0)
hxh.h(0)
print("HXH == Z:", Operator(hxh).equiv(Operator.from_label("Z")))
qc = QuantumCircuit(2)
qc.cx(0, 1)
U = Operator(qc)
print(np.real(U.data).astype(int))
print("unitary:", U.is_unitary())
print("U^dagger U = I:", np.allclose(U.data.conj().T @ U.data, np.eye(4)))
swap3 = QuantumCircuit(2)
swap3.cx(0, 1)
swap3.cx(1, 0)
swap3.cx(0, 1)
ref = QuantumCircuit(2)
ref.swap(0, 1)
print("3 CNOT == SWAP:", Operator(swap3).equiv(Operator(ref)))
Line-by-line code explanation
| Line | Explanation |
|---|---|
| 1-3 | Imports. |
| 5-8 | A circuit of H, then X, then H. |
| 9 | Compare its operator with the Z operator. |
| 11-12 | A CNOT circuit. |
| 13 | Its unitary matrix. |
| 14 | Print the real part as integers. |
| 15 | The built-in unitarity check. |
| 16 | Check U†U = I by hand. |
| 18-21 | Three CNOT gates in alternating directions. |
| 22-23 | A reference SWAP circuit. |
| 24 | Compare the two operators. |
Expected output (from an actual run)
HXH == Z: True [[1 0 0 0] [0 0 0 1] [0 0 1 0] [0 1 0 0]] unitary: True U^dagger U = I: True 3 CNOT == SWAP: True
The output is deterministic.
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.
