|q⟩ Bad Qubits

beginner · Programming · Building & Reading Quantum Circuits

Translating Math to Circuits

So far you have applied individual gates. Real algorithms are built from sequences of gates, and those sequences are most precisely described by matrix products. This lesson bridges the gap: given a matrix expression, how do you turn it into working code?

Matrix products are written backwards from circuit order

In linear algebra, the expression U=ABU = AB means "BB acts first, then AA." This right-to-left convention is inherited from function composition — fgf \circ g means apply gg first. A circuit diagram, and the programming API, use the opposite convention: gates are written and called in the order they fire, left to right.

The translation rule is therefore:

Reverse the product. If the math says U=AnA2A1U = A_n \cdots A_2 A_1, the circuit applies A1A_1 first, then A2A_2, and so on, ending with AnA_n.

For a two-step example:

U=ZHc.h(0); c.z(0);U = Z H \quad \Longrightarrow \quad \texttt{c.h(0); c.z(0);}

HH is on the right in the product, so it fires first; ZZ is on the left, so it fires second.

Tensor products and multi-qubit gates

When an expression uses the tensor product \otimes, it means two gates act on different qubits simultaneously. For instance, HIH \otimes I means: apply HH to qubit 0 and the identity II (do nothing) to qubit 1, both at the same time. In code, you simply call c.h(0) and omit qubit 1 — not calling a gate on a qubit is the same as placing II on that wire.

A multi-qubit gate like CNOT is written CNOT0,1\text{CNOT}_{0,1}, indicating qubit 0 is the control and qubit 1 is the target. In code that is c.cx(0, 1).

A worked example: the Bell-state preparation unitary

Consider the two-qubit matrix product

U=CNOT0,1(H0I1).U = \text{CNOT}_{0,1} \cdot (H_0 \otimes I_1).

Reading right to left, the time order is:

  1. Apply HH to qubit 0 (the H0I1H_0 \otimes I_1 factor fires first).
  2. Apply CNOT with qubit 0 as control and qubit 1 as target.

In code:

const c = circuit(2);
c.h(0);      // H ⊗ I fires first
c.cx(0, 1);  // CNOT fires second
return c;

You can verify this matches the matrix product by multiplying 4×44 \times 4 matrices: the CNOT matrix times the HIH \otimes I matrix reproduces the unitary of the Bell-state preparation circuit.

Try it

Implement the unitary U=CNOT0,1(H0I1)U = \text{CNOT}_{0,1} \cdot (H_0 \otimes I_1) on a two-qubit circuit. The grader checks the full 4×44 \times 4 unitary matrix, so the gate order must be exactly right.

Run your code to see the quantum state.

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