|q⟩ Bad Qubits

beginner · Programming · Building & Reading Quantum Circuits

Translating Circuits to Math

Every quantum circuit has an equivalent mathematical description: a unitary matrix UU that maps input states to output states. Being able to derive that matrix from the diagram is one of the most useful skills in quantum computing — it lets you predict outputs without running a simulator, spot gate identities, and debug circuits by inspection.

Each gate is a matrix; composition is multiplication

A single-qubit gate is a 2×22 \times 2 unitary matrix. The familiar Pauli and Hadamard matrices are:

X=(0110),Z=(1001),H=12(1111).X = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}, \quad Z = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}, \quad H = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix}.

When a circuit applies gate AA first and then gate BB, the combined operation is BAB \cdot A — matrix multiplication with the later gate on the left. For three gates applied in order G1G_1, G2G_2, G3G_3, the total unitary is U=G3G2G1U = G_3 G_2 G_1.

A worked example: HXHH \cdot X \cdot H

Let us derive the unitary for the three-gate sequence HH, XX, HH. First compute XHX \cdot H:

XH=(0110)12(1111)=12(1111).X \cdot H = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix} = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & -1 \\ 1 & 1 \end{pmatrix}.

Now multiply on the left by HH:

H(XH)=12(1111)12(1111)=12(2002)=(1001)=Z.H \cdot (X \cdot H) = \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix} \cdot \frac{1}{\sqrt{2}}\begin{pmatrix} 1 & -1 \\ 1 & 1 \end{pmatrix} = \frac{1}{2}\begin{pmatrix} 2 & 0 \\ 0 & -2 \end{pmatrix} = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix} = Z.

The circuit HXHH \to X \to H is exactly the ZZ gate. This makes geometric sense on the Bloch sphere: HH swaps the zz- and xx-axes, so a flip about the xx-axis (which is what XX does) becomes, after swapping axes back with HH, a flip about the zz-axis — and that is precisely ZZ.

Why unitarity matters

Every physically valid quantum operation must be unitary: UU=IU^\dagger U = I. Unitarity preserves the total probability (the norm of the state vector) and guarantees reversibility — you can always undo a unitary by applying UU^\dagger. For the example above, Z=ZZ^\dagger = Z (it is its own inverse), so HXHHXH=ZZ=IH X H H X H = Z Z = I, confirming reversibility.

Try it

Implement the circuit HXHH \to X \to H, whose unitary is ZZ. The grader compares the full 2×22 \times 2 unitary of your circuit, so returning an empty circuit will not pass.

Run your code to see the quantum state.

After running, open the Unitary tab to see the resulting matrix: it should be diagonal with entries 11 and 1-1, exactly matching ZZ.

Sign in on the full site to ask questions and join the discussion.