---
title: Quantum gates and circuits
heading: Building computations from one- and two-qubit operations
eyebrow: B10 · Lesson 45 · Quantum gates and circuits
xp: 40
---

::: hook
Lesson 26 turned a qubit with a timed microwave pulse: a single-qubit gate. Lesson 44 showed that two qubits can share an entangled state with no classical counterpart. A quantum computer is built from just these pieces: single-qubit rotations and one two-qubit gate that can entangle, arranged in a circuit and followed by measurement. This lesson writes the gates as matrices, builds an entangled pair from scratch, runs a small algorithm that beats any classical one, and counts what errors cost, which is why a superconducting processor's gate fidelity is quoted to three or four nines.
:::

::: play
- A circuit of $N$ gates, each succeeding with fidelity $F$, gives the right answer with probability about $F^N$. The curve shows that against $N$.
- At 99% per gate, a hundred gates leave a 37% chance of success; at 99.9%, 90%. Deep circuits need either much better gates or error correction.
:::

```sim plot
view: graph
x: N = 1..10000 log
y: P = 0..1
slider: e = 0.0001..0.02 step 0.0001 = 0.001
plot: (1 - e)^N | label: chance every gate succeeds
readout: gates for a 50% chance = ln(0.5)/ln(1 - e) | digits: 4
```

::: predict
## A Hadamard gate takes $|0\rangle$ to $(|0\rangle + |1\rangle)/\sqrt2$. What does a second Hadamard do to that state?

- [x] Returns it to $|0\rangle$
- [ ] Takes it to $|1\rangle$
- [ ] Leaves it as $(|0\rangle + |1\rangle)/\sqrt2$
- [ ] Measures it, giving 0 or 1 at random

::: reveal
It returns it to $|0\rangle$: $H^2 = I$. The two paths to $|1\rangle$ arrive with opposite signs and cancel, while the paths to $|0\rangle$ add. That interference, impossible with classical probabilities, is what quantum algorithms exploit: arrange the paths so wrong answers cancel and right ones add.
:::
:::

::: nameit
## Single-qubit gates

With $|0\rangle = \binom10$ and $|1\rangle = \binom01$, gates are $2 \times 2$ unitary matrices:

$$X = \begin{bmatrix}0 & 1\\1 & 0\end{bmatrix} \quad Z = \begin{bmatrix}1 & 0\\0 & -1\end{bmatrix} \quad H = \frac{1}{\sqrt2}\begin{bmatrix}1 & 1\\1 & -1\end{bmatrix} \quad R_z(\phi) = \begin{bmatrix}1 & 0\\0 & e^{j\phi}\end{bmatrix}$$

$X$ flips (a NOT gate), $Z$ flips the phase, $H$ makes equal superpositions, and $R_z$ turns the phase. On hardware each is a calibrated pulse, a rotation on lesson 26's Bloch sphere.

## Two qubits and the CNOT

Two qubits live in a four-dimensional space with basis $|00\rangle, |01\rangle, |10\rangle, |11\rangle$ (first qubit first). The **controlled-NOT** flips the second qubit when the first is 1:

$$\text{CNOT} = \begin{bmatrix}1 & 0 & 0 & 0\\0 & 1 & 0 & 0\\0 & 0 & 0 & 1\\0 & 0 & 1 & 0\end{bmatrix}$$

A gate on one qubit alone is a **Kronecker product** with the identity: $H$ on the first qubit is $H \otimes I$. Single-qubit gates plus CNOT are **universal**: any unitary on any number of qubits can be built from them.

## A Bell pair

Start in $|00\rangle$, apply $H$ to the first qubit, then CNOT:

$$|00\rangle \xrightarrow{H \otimes I} \frac{|00\rangle + |10\rangle}{\sqrt2} \xrightarrow{\text{CNOT}} \frac{|00\rangle + |11\rangle}{\sqrt2}$$

Measuring either qubit gives 0 or 1 at random, but the two always agree: lesson 44's entangled state, made with two gates.

## Measurement

A measurement in the $|0\rangle, |1\rangle$ basis returns each outcome with probability $|\text{amplitude}|^2$ and leaves the qubit in that state. To learn an amplitude you repeat the whole circuit many times; to measure in another basis you rotate first.

## Errors

Each gate succeeds with fidelity $F = 1 - \varepsilon$, so a circuit of $N$ gates succeeds with probability about $F^N \approx e^{-N\varepsilon}$, and each qubit loses its state over its coherence time $T_2$. With 30 ns gates and $T_2$ = 100 µs, a qubit lasts about 3300 gate times. Error correction encodes one logical qubit in many physical ones, and only works once $\varepsilon$ is below a threshold near 1%.
:::

::: example
## Apply $H$ twice to $|0\rangle$, writing out the matrices.

::: solution
1. **First Hadamard.**
   $$H|0\rangle = \frac{1}{\sqrt2}\binom11$$
2. **Second Hadamard.**
   $$\begin{aligned} H\left(\frac{1}{\sqrt2}\binom11\right) &= \frac12\binom{1 + 1}{1 - 1} \\ &= \binom10 \\ &= |0\rangle \end{aligned}$$
3. **Why |1⟩ cancels.** The $|1\rangle$ amplitude is $\frac12(1 - 1) = 0$: two paths, one through $|0\rangle$ and one through $|1\rangle$, with opposite signs.
4. **Measuring in between.** Measuring between the two Hadamards would destroy that cancellation and leave a 50-50 result.

**Answer:** two Hadamards bring $|0\rangle$ back to $|0\rangle$.
:::
:::

::: example
## Deutsch's problem: a black-box function $f$ takes one bit to one bit. Is it constant ($f(0) = f(1)$) or balanced? Classically you must evaluate $f$ twice. Show how one quantum evaluation suffices.

::: solution
1. **Prepare.** Start in $|0\rangle|1\rangle$ and apply $H$ to both qubits.
2. **Query the box once.** It maps $|x\rangle|y\rangle \to |x\rangle|y \oplus f(x)\rangle$. The second qubit, in $(|0\rangle - |1\rangle)/\sqrt2$, turns the query into a phase $(-1)^{f(x)}$ on the first qubit's $|x\rangle$, so the first qubit becomes
   $$\frac{1}{\sqrt2}\left((-1)^{f(0)}|0\rangle + (-1)^{f(1)}|1\rangle\right)$$
3. **Hadamard and measure.** Apply $H$ to the first qubit and measure it. The Hadamard sends that state to $\pm|0\rangle$ if $f$ is constant and $\pm|1\rangle$ if balanced.
4. **One query.** One query, a certain answer: the global property was read out through interference.

**Answer:** after one query and a final Hadamard, the first qubit reads 0 if $f$ is constant and 1 if it's balanced.
:::
:::

::: example
## A processor's two-qubit gates have 99.5% fidelity and its single-qubit gates 99.95%. Estimate the success probability of a circuit with 40 two-qubit and 120 single-qubit gates.

::: solution
1. **Two-qubit gates.**
   $$0.995^{40} = 0.818$$
2. **Single-qubit gates.**
   $$0.9995^{120} = 0.942$$
3. **The whole circuit.**
   $$0.818 \times 0.942 = 0.771$$
4. **Which gates cost more.** The two-qubit gates, fewer but ten times as error-prone, cost three times as much. That's why circuit compilers work hardest to minimize two-qubit gates, and why two-qubit fidelity is the headline number for a quantum processor.

**Answer:** the circuit succeeds with probability of about 0.771.
:::
:::

::: check
given: e = 0.01 | 0.001 | 0.0001; N = 100 | 1000 | 10000
answer: (1 - e)^N
tolerance: 0.5%

## A circuit has {N} gates, each with an error probability of {e}. About what is the chance all of them succeed?

::: right
Right. $(1 - \varepsilon)^N$ = {answer}, close to $e^{-N\varepsilon}$.
:::

::: misses
- [1 - e] That's one gate.
- [any] Not yet. Multiply the success probability of every gate: $(1 - \varepsilon)^N$.
:::
:::

::: check
kind: parts
given: a = 0..1 int

## Start in $|\given{a}\rangle$ and apply a Hadamard gate.

::: part
answer: 1/sqrt(2)
tolerance: 0.5%

### What is the amplitude of $|0\rangle$ afterward?

::: misses
- [1/2] That's the probability. The amplitude is its square root, $1/\sqrt2$.
- [any] Not yet. Multiply $H$ by the column for $|\given{a}\rangle$ and read the top entry.
:::
:::

::: part
answer: (1 - 2*a)/sqrt(2)
tolerance: 0.5%

### And of $|1\rangle$?

::: misses
- [any] Not yet. Read the bottom entry of $H$'s column number {a} (counting from 0).
:::
:::

::: right
Right. Both inputs give equal-weight superpositions, told apart only by the sign of the $|1\rangle$ amplitude, which a second Hadamard turns back into a definite 0 or 1.
:::
:::

::: check
kind: python
given: k = 0 | 1 | 2 | 3

## Using NumPy, build `H`, `I2` and `CNOT` as matrices and start from the two-qubit state whose basis index is `k` = {k} ($|00\rangle, |01\rangle, |10\rangle, |11\rangle$ are 0 to 3). Apply $H$ to the first qubit (`np.kron(H, I2)`), then CNOT. Set `psi` to the final state and `probs` to the four measurement probabilities.

```python starter
import numpy as np
psi = np.zeros(4); psi[k] = 1
probs = np.abs(psi)**2
print(psi, probs)
```

```python solution
import numpy as np
H = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
I2 = np.eye(2)
CNOT = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]])
psi = np.zeros(4); psi[k] = 1
psi = CNOT @ np.kron(H, I2) @ psi
probs = np.abs(psi)**2
print(psi, probs)
```

```python tests
import numpy as np
s = 1 / np.sqrt(2)
want = [np.array([s, 0, 0, s]), np.array([0, s, s, 0]), np.array([s, 0, 0, -s]), np.array([0, s, -s, 0])][k]
assert np.allclose(psi, want), f"Starting from basis state {k} the result should be the Bell state {np.round(want, 4)}."
assert np.allclose(probs, np.abs(want)**2) and abs(probs.sum() - 1) < 1e-12, "probs are the squared sizes of the amplitudes."
```

::: right
Right. The four inputs give the four Bell states, each an equal superposition of two outcomes that always agree (or always disagree). The phases, invisible in `probs`, are what tell them apart, and a reverse circuit would read them out.
:::
:::

::: check
kind: python
given: f = 0 | 1 | 2 | 3

## Simulate Deutsch's algorithm for the one-bit function picked by `f` = {f}: 0 is $f(x) = 0$, 1 is $f(x) = 1$, 2 is $f(x) = x$, 3 is $f(x) = 1 - x$. Build the oracle as a $4 \times 4$ matrix mapping $|x, y\rangle \to |x, y \oplus f(x)\rangle$, start from $|01\rangle$, apply $H \otimes H$, the oracle, then $H \otimes I$, and set `p1` to the probability that the first qubit is 1, and `balanced` to whether `p1 > 0.5`.

```python starter
import numpy as np
p1 = 0.5
balanced = False
print(p1, balanced)
```

```python solution
import numpy as np
H = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
I2 = np.eye(2)
fx = [lambda x: 0, lambda x: 1, lambda x: x, lambda x: 1 - x][f]
U = np.zeros((4, 4))
for x in (0, 1):
    for y in (0, 1):
        U[2 * x + (y ^ fx(x)), 2 * x + y] = 1
psi = np.zeros(4); psi[1] = 1
psi = np.kron(H, I2) @ U @ np.kron(H, H) @ psi
p1 = np.abs(psi[2])**2 + np.abs(psi[3])**2
balanced = bool(p1 > 0.5)
print(p1, balanced)
```

```python tests
want = f >= 2
assert abs(p1 - (1.0 if want else 0.0)) < 1e-12, f"For this function the first qubit should read {1 if want else 0} with certainty."
assert balanced == want, "balanced is p1 > 0.5."
```

::: right
Right. One query decides the question with certainty, where a classical program needs two. The speedup is small here, but the same interference trick, scaled up, gives Shor's and Grover's algorithms.
:::
:::

::: check
given: g = 20 | 30 | 100; T2 = 50 | 100 | 500
answer: T2*1e-6/(g*1e-9)
tolerance: 0.5%

## A qubit's coherence time is {T2} µs and its gates take {g} ns. About how many gate times fit in one coherence time?

::: right
Right. {T2} µs over {g} ns is {answer} gate times, an upper bound on useful circuit depth before errors from decoherence pile up.
:::

::: misses
- [T2/g] Convert both to seconds: microseconds over nanoseconds is a factor of 1000.
- [any] Not yet. Divide the coherence time by the gate time in the same units.
:::
:::

::: check
kind: derivation
vars: a = -1..1, b = -1..1

## Apply $H$ to a general state $a|0\rangle + b|1\rangle$ with real amplitudes.

::: step
answer: (a + b)/sqrt(2)

### What is the new amplitude of $|0\rangle$?
:::

::: step
answer: (a - b)/sqrt(2)

### And of $|1\rangle$?
:::

::: step
answer: a

### Apply $H$ again. What is the amplitude of $|0\rangle$ now?
:::

::: right
Right. $H^2 = I$: each output amplitude is a sum of two paths, and the second Hadamard makes the $b$ paths cancel in $|0\rangle$ and add in $|1\rangle$.
:::
:::

::: check
kind: choice

## Why does a Hadamard on the first qubit followed by a CNOT entangle two qubits, while either gate alone does not?

- [x] The Hadamard puts the control in a superposition, and the CNOT then makes the target's state depend on which branch the control is in
- [ ] The Hadamard entangles them and the CNOT only checks it
- [ ] CNOT always entangles any input
- [ ] Two gates in a row always entangle

::: right
Right. CNOT on a definite control just flips or doesn't, leaving a product state; given a superposed control, it correlates the target with each branch, and the result can't be written as one qubit's state times the other's.
:::

::: misses
- [2] A gate on one qubit can never entangle; it only changes that qubit's own state.
- [3] On $|00\rangle$ or $|10\rangle$ the CNOT gives another product state.
- [4] Two single-qubit gates in a row never entangle; you need a two-qubit gate acting on a superposition.
:::
:::

::: explain
## Why is a circuit's success probability so sensitive to the error rate per gate, and what does that imply for building a useful quantum computer?

::: model
Every gate must succeed for the computation to be right, so the success probabilities multiply: $N$ gates at error $\varepsilon$ give about $e^{-N\varepsilon}$. That falls off exponentially once $N\varepsilon$ is near 1, so a circuit's useful depth is roughly $1/\varepsilon$ gates: a hundred at 1% error, ten thousand at 0.01%. Useful algorithms need millions of gates or more, far beyond any physical error rate, so a practical machine must use error correction, spreading each logical qubit over many physical ones and repeatedly detecting and fixing errors, which works only once the physical error rate is below the code's threshold.
:::
:::

::: practice

::: check
given: N = 50 | 200; e = 0.005 | 0.0005
answer: exp(-N*e)
tolerance: 1%

## Approximately, what is $(1 - \given{e})^{\given{N}}$, using $e^{-N\varepsilon}$?

::: misses
- [any] $e^{-N\varepsilon}$.
:::
:::

::: check
given: e = 0.05 | 0.01 | 0.005 | 0.001 | 0.0001
answer: ln(0.5)/ln(1 - e)
tolerance: 0.5%

## With per-gate error {e}, after how many gates does the success probability fall to 50%?

::: misses
- [0.5/e] Solve $(1 - \varepsilon)^N = 0.5$ with logarithms.
- [any] $N = \ln 0.5/\ln(1 - \varepsilon)$.
:::
:::
:::
