You have the state of a qubit and you want to transform it: move it from 0 to 1, put it in superposition, tie it to a second qubit. A quantum circuit is a sequence of these transformations, and each one is a matrix. The constraint that defines them is only one: the matrix must be unitary, that is $U^\dagger U = I$. It preserves the norm of the vector (the probabilities keep summing to one) and it is invertible, because $U^\dagger$ undoes it. Every "gate" you will meet, from Hadamard to CNOT, is a special case, and very few are enough to build any transformation.
In this lesson (the second of Quantum Computing in Italiano, after qubits and superposition) you check with three NumPy listings the identities you need, prove that a finite set of gates approximates an arbitrary rotation, and build a real circuit, the Toffoli gate, counting the pieces. Everything is local simulation with Python 3.14.4 and NumPy 2.5.4; the construction of the Toffoli was repeated with Qiskit 2.6.2.
Single-qubit gates: one matrix, one effect on the sphere
There are six matrices you use almost all the time (in the table below $Y$ has no row of its own and appears only in the identities). The three Pauli matrices $X, Y, Z$ are half-turn rotations about the three axes of the Bloch sphere (up to a global phase): $X$ swaps $|0\rangle$ and $|1\rangle$ and is the quantum NOT, while $Z$ leaves $|0\rangle$ alone and flips the sign of $|1\rangle$, that is it shifts the relative phase. The Hadamard gate $H$ turns the basis $\{|0\rangle,|1\rangle\}$ into the basis $\{|+\rangle,|-\rangle\}$. The two phase gates $S = \mathrm{diag}(1, i)$ and $T = \mathrm{diag}(1, e^{i\pi/4})$ rotate about $Z$ by a quarter and an eighth of a turn respectively.
| Gate | Matrix | What it does | Identity the listing checks |
|---|---|---|---|
| $X$ | $\begin{pmatrix}0&1\\1&0\end{pmatrix}$ | swaps 0 and 1 | $XY = iZ$ |
| $Z$ | $\begin{pmatrix}1&0\\0&-1\end{pmatrix}$ | flips the sign of $|1\rangle$ | $HZH = X$ |
| $H$ | $\tfrac{1}{\sqrt2}\begin{pmatrix}1&1\\1&-1\end{pmatrix}$ | changes basis between $Z$ and $X$ | $HXH = Z$, $HYH = -Y$, $H^2 = I$ |
| $S$ | $\mathrm{diag}(1, i)$ | quarter-turn phase | $S^2 = Z$ |
| $T$ | $\mathrm{diag}(1, e^{i\pi/4})$ | eighth-turn phase | $T^2 = S$, $T^8 = I$ |
The right-hand column is what you will use to reason about circuits without computing by hand: $HZH = X$ says that putting a $Z$ between two Hadamards is equivalent to an $X$, and it is the reason why circuit C of the previous article (H, Z, H) takes $|0\rangle$ to $|1\rangle$. The Pauli matrices and $H$ are the ones that define the identities, $S$ and $T$ are successive roots of $Z$.
CNOT and two-qubit gates
The two-qubit gate you need is the CNOT: if the control qubit is 1 it flips the target, otherwise it does nothing. On the basis $|00\rangle, |01\rangle, |10\rangle, |11\rangle$ it is the matrix that swaps the last two columns. Its cousin CZ flips the sign of $|11\rangle$ only, and is symmetric between the two qubits. The two gates are the same operation seen in different bases: surrounding the target with two Hadamards turns CZ into CNOT. With the same trick, a Hadamard on each qubit before and after swaps the roles of control and target. Three alternating CNOTs swap the two qubits (SWAP).
import numpy as np
I2 = np.eye(2)
X = np.array([[0, 1], [1, 0]], dtype=complex)
Y = np.array([[0, -1j], [1j, 0]])
Z = np.array([[1, 0], [0, -1]], dtype=complex)
H = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
S = np.diag([1, 1j])
T = np.diag([1, np.exp(1j * np.pi / 4)])
CNOT = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]], dtype=complex)
CZ = np.diag([1, 1, 1, -1]).astype(complex)
SWAP = np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]], dtype=complex)
def is_unitary(U):
return np.allclose(U.conj().T @ U, np.eye(len(U)))
def equal(A, B):
return np.allclose(A, B)
print("all unitary:", all(is_unitary(U) for U in (X, Y, Z, H, S, T, CNOT, CZ, SWAP)))
print("H X H = Z :", equal(H @ X @ H, Z))
print("H Z H = X :", equal(H @ Z @ H, X))
print("H Y H = -Y :", equal(H @ Y @ H, -Y))
print("X Y = i Z :", equal(X @ Y, 1j * Z))
print("S S = Z :", equal(S @ S, Z))
print("T T = S :", equal(T @ T, S))
print("T^8 = I :", equal(np.linalg.matrix_power(T, 8), I2))
print("H H = I :", equal(H @ H, I2))
print("H then S differs from S then H:", not equal(S @ H, H @ S))
print("CNOT = (I x H) CZ (I x H):", equal(np.kron(I2, H) @ CZ @ np.kron(I2, H), CNOT))
flipped_cnot = np.kron(H, H) @ CNOT @ np.kron(H, H)
CNOT_21 = np.array([[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 1, 0, 0]], dtype=complex)
print("(H x H) CNOT (H x H) = CNOT with control and target swapped:", equal(flipped_cnot, CNOT_21))
print("SWAP = CNOT01 CNOT10 CNOT01:", equal(CNOT @ CNOT_21 @ CNOT, SWAP))
# ZYZ decomposition: U = e^{i delta} Rz(alpha) Ry(beta) Rz(gamma)
def Rz(t): return np.diag([np.exp(-1j * t / 2), np.exp(1j * t / 2)])
def Ry(t): return np.array([[np.cos(t / 2), -np.sin(t / 2)], [np.sin(t / 2), np.cos(t / 2)]], dtype=complex)
def zyz(U):
delta = np.angle(np.linalg.det(U)) / 2
V = U * np.exp(-1j * delta) # now det V = 1
a, b = V[0, 0], V[1, 0]
beta = 2 * np.arctan2(abs(b), abs(a))
total, diff = -2 * np.angle(a), 2 * np.angle(b) # alpha+gamma, alpha-gamma
return delta, (total + diff) / 2, beta, (total - diff) / 2
rng = np.random.default_rng(7)
worst = 0.0
for _ in range(1000):
M = rng.normal(size=(2, 2)) + 1j * rng.normal(size=(2, 2))
Q, R = np.linalg.qr(M)
U = Q * (np.diag(R) / abs(np.diag(R))) # random unitary
d, al, be, ga = zyz(U)
error = np.abs(np.exp(1j * d) * Rz(al) @ Ry(be) @ Rz(ga) - U).max()
worst = max(worst, error)
print("ZYZ on 1000 random unitaries, maximum error < 1e-12:", worst < 1e-12)
# Output:
# all unitary: True
# H X H = Z : True
# H Z H = X : True
# H Y H = -Y : True
# X Y = i Z : True
# S S = Z : True
# T T = S : True
# T^8 = I : True
# H H = I : True
# H then S differs from S then H: True
# CNOT = (I x H) CZ (I x H): True
# (H x H) CNOT (H x H) = CNOT with control and target swapped: True
# SWAP = CNOT01 CNOT10 CNOT01: True
# ZYZ on 1000 random unitaries, maximum error < 1e-12: True
The first group of lines checks that every matrix is unitary (U.conj().T @ U equal to the identity) and then verifies one by one the identities of the table with np.allclose. The output is True everywhere, including the line H then S differs from S then H: order matters, because the product of matrices does not commute. In a circuit drawn from left to right, the first gate is the rightmost matrix in the product: S @ H means "first H, then S". It is the most common mistake of those who move from the drawing to the code.
The three lines on the CNOT concern the change-of-basis trick. np.kron(I2, H) applies H to the second qubit only, and np.kron(I2, H) @ CZ @ np.kron(I2, H) rebuilds the CNOT exactly. np.kron(H, H) on the two qubits, before and after, produces the CNOT with the roles reversed, and CNOT @ CNOT_21 @ CNOT is the SWAP. The final block concerns a different fact, namely that every single-qubit gate is a ZYZ rotation, and I explain it right away.
Every single-qubit gate is three rotations
Any 2×2 unitary matrix can be written as $U = e^{i\delta} R_z(\alpha) R_y(\beta) R_z(\gamma)$, with $R_z(t) = \mathrm{diag}(e^{-it/2}, e^{it/2})$ and $R_y$ the real rotation about $y$. The function zyz of the listing recovers the four angles: the phase $\delta$ from the determinant, $\beta$ from the ratio between the moduli of the elements of the first column (np.arctan2), and $\alpha \pm \gamma$ from the phases. On the thousand random unitary matrices generated with a fixed seed, the maximum reconstruction error stays below $10^{-12}$. The test uses random matrices: for $\beta = 0$ or $\beta = \pi$ only the sum or the difference of $\alpha$ and $\gamma$ is determined, and the decomposition is not unique. The practical result is that hardware with only rotations about $z$ and $y$ (or equivalents) realizes any single-qubit gate.
How many gates are enough: universality
Barenco and colleagues showed in 1995 that arbitrary single-qubit gates together with the CNOT are enough to obtain every unitary on $n$ qubits (abstract of "Elementary gates for quantum computation"). But "arbitrary" means infinitely many: hardware implements a finite set. Boykin and colleagues (1999) describe a finite basis, $H$, $T$ (which they write $\sigma_z^{1/4}$) and CNOT, universal in an approximate sense and suited to fault tolerance. Dawson and Nielsen present the Solovay-Kitaev algorithm, which compiles any single-qubit gate into a sequence of gates from a finite set efficiently. The abstract says the algorithm is efficient; I do not report its costs here, because I have not read the proof.
The second listing does not prove the theorem, but it lets you see what "approximate" means. It builds all the sequences of $H$ and $T$ up to 20 gates (more than a million matrices) and measures how close the best one gets to an assigned rotation, Ry(1.0).
import numpy as np
H = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
T = np.diag([1, np.exp(1j * np.pi / 4)])
def Ry(t):
return np.array([[np.cos(t / 2), -np.sin(t / 2)], [np.sin(t / 2), np.cos(t / 2)]], dtype=complex)
def distance(W, target):
# 0 if equal up to a global phase; W has shape (k,2,2)
ov = np.abs(np.einsum("kij,ij->k", W.conj(), target)) / 2
return np.sqrt(np.clip(1 - ov, 0, None))
target = Ry(1.0) # an arbitrary rotation, 1 radian about y
words = np.eye(2, dtype=complex)[None] # the empty word
best = np.inf
print("length words tried minimum distance (up to that length)")
for L in range(1, 21):
words = np.concatenate([H @ words, T @ words]) # each word is extended with H or with T
best = min(best, distance(words, target).min())
if L in (2, 4, 8, 12, 16, 20):
print(f"{L:6d} {len(words):11d} {best:.4f}")
# Output:
# length words tried minimum distance (up to that length)
# 2 4 0.3499
# 4 16 0.3369
# 8 256 0.0758
# 12 4096 0.0758
# 16 65536 0.0758
# 20 1048576 0.0503
The distance used is $d(U,V) = \sqrt{1 - |\mathrm{tr}(U^\dagger V)|/2}$, which is 0 when the matrices coincide up to a global phase (np.einsum computes it for all the sequences at once). The loop extends every sequence with H or with T, doubling the number of words at each round. There is no need to write $T^\dagger$: since $T^8 = I$, we have $T^\dagger = T^7$. The output shows three things. With 2 or 4 gates the distance stays around 0.35-0.34. At 8 gates it drops to 0.0758 and at 12 and 16 it does not improve, because the new sequences do not beat the best one already found. At 20 gates it reaches 0.0503. The gain grows in steps and costs a factor of 2 in sequences for every gate added: the exhaustive search does not scale, and this is exactly why a compilation algorithm is used instead.
The limit of this experiment: I tried a single target and a single family of sequences, so the numbers 0.0758 and 0.0503 are not a general measure of the precision reachable with a given length. They only serve to show the shape of the trade-off between length and precision.
A real circuit: the Toffoli gate
The Toffoli gate has two controls and one target: it flips the target only if both controls are 1. It is not in the set $\{H, T, \mathrm{CNOT}\}$, so it has to be built. The third listing realizes it with 15 gates, and first of all you need a multi-qubit simulator. The function apply_1q uses np.tensordot to multiply the 2×2 matrix along the axis of the chosen qubit and np.moveaxis to put the axis back in its place: it never builds the $2^n \times 2^n$ matrix. The function apply_cnot selects with a slice the amplitudes in which the control is 1 and flips the target axis with np.flip. The target axis changes index when the control's one is removed, and this is the line axis = t if t < c else t - 1. Qubit 0 is the leftmost one, the convention of the previous article.
import numpy as np
# Convention: qubit 0 is the leftmost one (the most significant bit)
def apply_1q(state, U, q, n):
t = state.reshape((2,) * n)
t = np.moveaxis(np.tensordot(U, t, axes=([1], [q])), 0, q)
return t.reshape(-1)
def apply_cnot(state, c, t, n):
out = state.reshape((2,) * n).copy()
idx = [slice(None)] * n
idx[c] = 1 # only where the control is 1
sub = out[tuple(idx)]
axis = t if t < c else t - 1 # the target axis after removing c
out[tuple(idx)] = np.flip(sub, axis=axis) # swap 0 and 1 of the target
return out.reshape(-1)
H = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
T = np.diag([1, np.exp(1j * np.pi / 4)])
Td = T.conj().T
# Toffoli (controls 0 and 1, target 2) with H, T, T^dagger, CNOT
circuit = [("h", 2), ("cx", 1, 2), ("td", 2), ("cx", 0, 2), ("t", 2), ("cx", 1, 2),
("td", 2), ("cx", 0, 2), ("t", 1), ("t", 2), ("h", 2), ("cx", 0, 1),
("t", 0), ("td", 1), ("cx", 0, 1)]
gate = {"h": H, "t": T, "td": Td}
def run(state):
for g in circuit:
if g[0] == "cx":
state = apply_cnot(state, g[1], g[2], 3)
else:
state = apply_1q(state, gate[g[0]], g[1], 3)
return state
ok = True
for k in range(8):
basis = np.zeros(8, dtype=complex)
basis[k] = 1
expected = np.zeros(8, dtype=complex)
expected[k ^ 1 if (k >> 2) & 1 and (k >> 1) & 1 else k] = 1 # bit 0 of the number = qubit 2
ok &= bool(np.allclose(run(basis), expected))
print("the circuit implements Toffoli on the 8 basis states:", ok)
count = {}
for g in circuit:
name = "T or T^dagger" if g[0] in ("t", "td") else g[0].upper()
count[name] = count.get(name, 0) + 1
print("gates:", count, "total", len(circuit))
# CNOT(0 -> 2) on |100> must give |101>
s = np.zeros(8, dtype=complex)
s[0b100] = 1
print("CNOT(0->2) on |100> ->", format(int(np.argmax(abs(apply_cnot(s, 0, 2, 3)))), "03b"))
# Output:
# the circuit implements Toffoli on the 8 basis states: True
# gates: {'H': 2, 'CX': 6, 'T or T^dagger': 7} total 15
# CNOT(0->2) on |100> -> 101
The output says three things. The circuit, applied to each of the eight basis states, produces exactly the output of a Toffoli: the comparison is with np.allclose on the complex vectors, so the phases coincide too, not just the probabilities. The count is 2 Hadamards, 6 CNOTs and 7 gates of type $T$ or $T^\dagger$, for 15 gates in all. The last line checks that apply_cnot(s, 0, 2, 3) takes |100> to |101>, that is that the control on qubit 0 acts on qubit 2 even if they are not adjacent. The same sequence built in Qiskit 2.6.2 produces an operator identical, phase included, to that of its ccx gate; the two ways of numbering the qubits do not come into play because the indices are the same in both.
The number 15 is the measure that matters when you think of real hardware: every gate has an error, and a circuit with more gates accumulates more errors. By how much depends on the machine, and it is not a datum of this article.
The mistakes made most often
- Writing the product of matrices in the order in which you draw the gates: the first gate is on the right.
- Mixing up control and target in the CNOT, or the order of the qubits between your code and Qiskit's, which numbers from the least significant bit as its documentation on bit ordering says.
- Using
np.allclosewithout accounting for a global phase when the comparison should ignore it, or ignoring it when it matters (a controlled phase is not global). - Thinking that two circuits with the same unitary cost the same: the Toffoli has a single effect but many realizations with different gate counts.
The four mistakes have the same root: a circuit is a mathematical object with several representations, and the code picks one. When two results do not coincide, the first check is always to bring them back to the same convention of order and phase.
What you can do now
You can write the standard gates as matrices, verify their identities with a numerical check, decompose a single-qubit gate into three rotations and rebuild a CNOT from a CZ. You have a simulator of a few lines that applies gates to one or two qubits of any register, and you have seen that building a known gate from a finite set takes dozens of gates. An oracle, like the one in the Deutsch-Jozsa problem, is a reversible gate of the same kind as the Toffoli: a permutation matrix. The next step is to use the CNOT to tie two qubits together: the lesson on entanglement starts from H plus CNOT.
Frequently asked questions
What does it mean for a quantum gate to be unitary?
It means that the matrix $U$ satisfies $U^\dagger U = I$. It preserves the norm of the state, so the probabilities still sum to one, and it is invertible: applying $U^\dagger$ brings you back to the starting state.
Are CNOT and CZ equivalent?
They are the same operation in different bases: surrounding the target with two Hadamard gates turns the CZ into the CNOT, as the first listing checks. The CZ is symmetric between the two qubits, the CNOT is not.
Do you really need a universal set of gates?
Yes, because hardware realizes only a finite set of gates. Arbitrary single-qubit gates plus the CNOT give every unitary (Barenco and colleagues, 1995), and the finite set H, T and CNOT also approximates any gate, with a precision that grows with the length of the sequence.
How many gates does a Toffoli need?
The construction verified in the article uses 15 gates: 2 Hadamards, 6 CNOTs and 7 T or inverse-T gates. It is not shown here that this is the minimum possible: it is a correct realization, executed and checked on all the basis states.
Later in the series you will also find Shor's algorithm (article 6) and VQE for chemistry (article 7).
Sources
- A. Barenco et al., "Elementary gates for quantum computation", arXiv:quant-ph/9503016 (1995) - single-qubit gates plus the CNOT are universal; abstract read, consulted on 2026-11-13
- P. O. Boykin et al., "On Universal and Fault-Tolerant Quantum Computing", arXiv:quant-ph/9906054 (1999) - the finite basis H, T and CNOT; abstract read, consulted on 2026-11-13
- C. M. Dawson, M. A. Nielsen, "The Solovay-Kitaev algorithm", arXiv:quant-ph/0505030 (2005) - the efficient compilation of a single-qubit gate into a finite set; abstract read, consulted on 2026-11-13
- Qiskit, "Bit-ordering in the Qiskit SDK" - the little-endian order of the qubits, read in the text of the page, consulted on 2026-11-13
The three listings were run twice with Python 3.14.4 and NumPy 2.5.4, with identical output. The construction of the Toffoli was also repeated with Qiskit 2.6.2 (current version on PyPI on 2026-11-13). Of the three arXiv papers I read only the abstract.
Commenti
Caricamento commenti...
Sign in to comment