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 means " acts first, then ." This right-to-left convention is inherited from function composition — means apply 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 , the circuit applies first, then , and so on, ending with .
For a two-step example:
is on the right in the product, so it fires first; is on the left, so it fires second.
Tensor products and multi-qubit gates
When an expression uses the tensor product , it means two gates act on different qubits
simultaneously. For instance, means: apply to qubit 0 and the identity (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 on that wire.
A multi-qubit gate like CNOT is written , 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
Reading right to left, the time order is:
- Apply to qubit 0 (the factor fires first).
- 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 matrices: the CNOT matrix times the matrix reproduces the unitary of the Bell-state preparation circuit.
Try it
Implement the unitary on a two-qubit circuit. The grader checks the full unitary matrix, so the gate order must be exactly right.
Sign in on the full site to ask questions and join the discussion.