Skip to main content
KetQat

Appearance

Lesson 345 min

Quantum gates and unitary transformations

Why quantum evolution is unitary, the standard single-qubit gates, and gates as Bloch-sphere rotations.

After this lesson you can

  • Show that a linear map preserving the norm of every state is unitary, and conclude that gates are reversible
  • Apply the Pauli, Hadamard, S, T, phase and rotation gates to states by matrix multiplication
  • Identify the Bloch-sphere rotation (axis and angle) performed by a single-qubit gate
  • Compose gates in the correct order and show with an example that order matters
  • State the ZYZ decomposition theorem and decompose a given single-qubit unitary numerically

Read first: Qubits and the Bloch sphere

What may a gate do to a state?

A gate is something we do to a qubit between preparation and measurement: a laser or microwave pulse, a precisely timed interaction. Whatever the hardware, the mathematical description has to respect two requirements.

  1. Linearity. If a gate maps ∣0⟩\ket0 to ∣a⟩\ket{a} and ∣1⟩\ket1 to ∣b⟩\ket{b}, it must map α∣0⟩+β∣1⟩\alpha\ket0 + \beta\ket1 to α∣a⟩+β∣b⟩\alpha\ket a + \beta\ket b. This is a postulate of quantum mechanics (closed systems evolve linearly), and it is what lets the interference of the first lesson happen path by path. A linear map on C2\C^2 is a 2×22\times2 matrix UU.
  2. States stay states. Every unit vector must be mapped to a unit vector, or the Born probabilities would stop adding to one.

These two requirements force UU to be unitary: U†U=IU^\dagger U = I, where U†U^\dagger is the conjugate transpose.

Proof. For every unit vector ∣ψ⟩\ket\psi we need 1=∥Uψ∥2=⟨ψ∣U†U∣ψ⟩1 = \norm{U\psi}^2 = \bra\psi U^\dagger U\ket\psi. Let A=U†U−IA = U^\dagger U - I. Then ⟨ψ∣A∣ψ⟩=0\bra\psi A\ket\psi = 0 for every unit ∣ψ⟩\ket\psi, hence (by scaling) for every vector. AA is Hermitian, so it has an orthonormal eigenbasis with real eigenvalues λk\lambda_k; choosing ∣ψ⟩\ket\psi to be an eigenvector gives λk=0\lambda_k = 0 for every kk, hence A=0A = 0. Conversely, if U†U=IU^\dagger U = I then ⟨Uϕ∣Uψ⟩=⟨ϕ∣U†U∣ψ⟩=⟨ϕ∣ψ⟩\braket{U\phi}{U\psi} = \bra\phi U^\dagger U \ket\psi = \braket\phi\psi: unitaries preserve all inner products, not only norms. □\square

A unitary matrix is invertible with U−1=U†U^{-1} = U^\dagger, which is itself unitary. So every gate can be undone by applying its adjoint. Classical logic is different: an AND gate maps both inputs 01 and 10 to output 0, so it cannot be reversed. Quantum gates never lose information in this way. The only irreversible step in a circuit is measurement, as the next lesson shows.

The standard single-qubit gates

The gates you will meet everywhere are, in the computational basis:

Gate Matrix Action on basis states
XX (0110)\begin{pmatrix}0&1\\1&0\end{pmatrix} ∣0⟩↔∣1⟩\ket0\leftrightarrow\ket1 (bit flip, NOT)
YY (0−ii0)\begin{pmatrix}0&-i\\i&0\end{pmatrix} ∣0⟩↦i∣1⟩\ket0\mapsto i\ket1, ∣1⟩↦−i∣0⟩\ket1\mapsto -i\ket0
ZZ (100−1)\begin{pmatrix}1&0\\0&-1\end{pmatrix} ∣1⟩↦−∣1⟩\ket1\mapsto-\ket1 (phase flip)
HH 12(111−1)\frac{1}{\sqrt2}\begin{pmatrix}1&1\\1&-1\end{pmatrix} ∣0⟩↦∣+⟩\ket0\mapsto\ket+, ∣1⟩↦∣−⟩\ket1\mapsto\ket-
P(λ)P(\lambda) (100eiλ)\begin{pmatrix}1&0\\0&e^{i\lambda}\end{pmatrix} ∣1⟩↦eiλ∣1⟩\ket1\mapsto e^{i\lambda}\ket1
SS P(π/2)=diag(1,i)P(\pi/2) = \mathrm{diag}(1, i)
TT P(π/4)=diag(1,eiπ/4)P(\pi/4) = \mathrm{diag}(1, e^{i\pi/4})

Useful relations, each a one-line matrix multiplication: T2=ST^2 = S, S2=ZS^2 = Z, H2=IH^2 = I, HXH=ZHXH = Z, HZH=XHZH = X, and X2=Y2=Z2=IX^2 = Y^2 = Z^2 = I. The Paulis are both unitary and Hermitian, so each is its own inverse; SS and TT are not Hermitian, and their inverses are S†=diag(1,−i)S^\dagger = \mathrm{diag}(1,-i) and T†T^\dagger.

Rotation gates

Since P2=IP^2 = I for each Pauli PP, the exponential series splits into even and odd terms:

RP(α)=e−iαP/2=cos⁡α2 I−isin⁡α2 P.R_P(\alpha) = e^{-i\alpha P/2} = \cos\frac\alpha2\, I - i\sin\frac\alpha2\, P .

More generally, for a real unit vector n⃗=(nx,ny,nz)\vec n = (n_x, n_y, n_z) the matrix n⃗⋅P⃗=nxX+nyY+nzZ\vec n\cdot\vec P = n_xX + n_yY + n_zZ also squares to II, and Rn⃗(α)=cos⁡α2I−isin⁡α2 n⃗⋅P⃗R_{\vec n}(\alpha) = \cos\frac\alpha2 I - i\sin\frac\alpha2\,\vec n\cdot\vec P. For example

RZ(α)=(e−iα/200eiα/2),RY(α)=(cos⁡α2−sin⁡α2sin⁡α2cos⁡α2).R_Z(\alpha) = \begin{pmatrix} e^{-i\alpha/2} & 0\\ 0 & e^{i\alpha/2}\end{pmatrix},\qquad R_Y(\alpha) = \begin{pmatrix} \cos\frac\alpha2 & -\sin\frac\alpha2\\ \sin\frac\alpha2 & \cos\frac\alpha2\end{pmatrix}.

Comparing RZ(λ)R_Z(\lambda) with P(λ)P(\lambda) shows P(λ)=eiλ/2RZ(λ)P(\lambda) = e^{i\lambda/2}R_Z(\lambda): the two differ only by a global phase, so they are the same physical operation on a single qubit. (The phase becomes relevant when a gate is controlled by another qubit, a point we return to in the algorithms lesson.)

Gates are rotations of the Bloch sphere

Here is the geometric fact that makes single-qubit gates easy to visualise.

Theorem. For a single qubit, Rn⃗(α)R_{\vec n}(\alpha) rotates every Bloch vector by angle α\alpha about the axis n⃗\vec n (right-hand rule). Every 2×22\times2 unitary equals eiγRn⃗(α)e^{i\gamma}R_{\vec n}(\alpha) for some phase γ\gamma, axis n⃗\vec n and angle α\alpha, so every single-qubit gate acts on the Bloch sphere as a rotation. (See Nielsen and Chuang, Section 4.2 and Exercise 4.6.)

The zz case can be checked by hand. Apply RZ(α)R_Z(\alpha) to the Bloch form:

RZ(α)(cos⁡θ2∣0⟩+eiφsin⁡θ2∣1⟩)=e−iα/2(cos⁡θ2∣0⟩+ei(φ+α)sin⁡θ2∣1⟩).R_Z(\alpha)\Big(\cos\tfrac\theta2\ket0 + e^{i\varphi}\sin\tfrac\theta2\ket1\Big) = e^{-i\alpha/2}\Big(\cos\tfrac\theta2\ket0 + e^{i(\varphi+\alpha)}\sin\tfrac\theta2\ket1\Big).

Up to the global phase e−iα/2e^{-i\alpha/2}, θ\theta is unchanged and φ\varphi increases by α\alpha: a rotation by α\alpha about zz. A relative phase gate is a turn around the vertical axis. The exercise checks the general statement numerically by computing the 3×33\times3 matrix Mij=12Tr⁡(Pi UPjU†)M_{ij} = \tfrac12\tr(P_i\,U P_j U^\dagger) that a gate applies to Bloch vectors.

Reading familiar gates as rotations:

  • X=iRX(π)X = iR_X(\pi): half a turn about xx, which swaps the poles.
  • Z=iRZ(π)Z = iR_Z(\pi): half a turn about zz, which swaps ∣+⟩\ket+ and ∣−⟩\ket-.
  • S=eiπ/4RZ(π/2)S = e^{i\pi/4}R_Z(\pi/2) and T=eiπ/8RZ(π/4)T = e^{i\pi/8}R_Z(\pi/4): quarter and eighth turns about zz.
  • H=iRn⃗(π)H = iR_{\vec n}(\pi) with n⃗=(1,0,1)/2\vec n = (1, 0, 1)/\sqrt2, because Rn⃗(π)=−i(X+Z)/2=−iHR_{\vec n}(\pi) = -i(X+Z)/\sqrt2 = -iH. Half a turn about the axis halfway between xx and zz exchanges those two axes and reverses yy; that is why HH maps ∣0⟩↔∣+⟩\ket0\leftrightarrow\ket+ and ∣+i⟩↔∣−i⟩\ket{+i}\leftrightarrow\ket{-i}.

Composition and order

A circuit is read left to right, in time order. Matrices act on the column vector from the left, so the circuit "first AA, then BB" is the matrix product BABA. Getting this backwards is the most common error in hand calculations.

Quantum circuit on 2 wires (a, b). step 1: H on a; S on b. step 2: S on a; H on b.abHSSH
Order matters: H then S (top) prepares |+i⟩; S then H (bottom) prepares |+⟩

Both wires start in ∣0⟩\ket0. On wire aa, SH∣0⟩=S∣+⟩=(∣0⟩+i∣1⟩)/2=∣+i⟩SH\ket0 = S\ket+ = (\ket0 + i\ket1)/\sqrt2 = \ket{+i}. On wire bb, HS∣0⟩=H∣0⟩=∣+⟩HS\ket0 = H\ket0 = \ket+, because SS only puts a phase on ∣1⟩\ket1, which ∣0⟩\ket0 does not have. Two different states; in Bloch terms, rotating ∣0⟩\ket0 to the xx axis and then a quarter turn about zz ends on the yy axis, while a quarter turn about zz does nothing to the north pole. Rotations about different axes do not commute, and neither do the gates.

Sometimes two orders differ only by a global phase, which is physically the same gate: ZX=iYZX = iY while XZ=−iYXZ = -iY. On a single qubit these two products do the same thing. You should always ask whether a difference is a global phase before concluding that two circuits disagree.

Universality: the ZYZ decomposition

How many different kinds of gate does a single-qubit processor need? Very few.

Theorem (ZYZ decomposition). For every 2×22\times2 unitary UU there are real numbers α,β,γ,δ\alpha, \beta, \gamma, \delta such that

U=eiα RZ(β) RY(γ) RZ(δ).U = e^{i\alpha}\, R_Z(\beta)\, R_Y(\gamma)\, R_Z(\delta).

(Nielsen and Chuang, Theorem 4.1.) So rotations about just two fixed axes, zz and yy, reach every single-qubit gate. The angles are easy to find. Multiplying out the three rotations gives

RZ(β)RY(γ)RZ(δ)=(e−i(β+δ)/2cos⁡γ2−e−i(β−δ)/2sin⁡γ2ei(β−δ)/2sin⁡γ2ei(β+δ)/2cos⁡γ2),R_Z(\beta)R_Y(\gamma)R_Z(\delta) = \begin{pmatrix} e^{-i(\beta+\delta)/2}\cos\frac\gamma2 & -e^{-i(\beta-\delta)/2}\sin\frac\gamma2\\ e^{i(\beta-\delta)/2}\sin\frac\gamma2 & e^{i(\beta+\delta)/2}\cos\frac\gamma2 \end{pmatrix},

which has determinant 1. So e2iα=det⁡Ue^{2i\alpha} = \det U fixes α\alpha (up to adding π\pi, which is absorbed by the other angles). Dividing UU by eiαe^{i\alpha} leaves a matrix of the form above: the moduli of its entries give γ\gamma, and the phases of the left column give β+δ\beta+\delta and β−δ\beta-\delta. When γ=0\gamma=0 or γ=π\gamma=\pi only one of these combinations is determined, and any split works.

Worked example: the Hadamard gate

For HH, det⁡H=−1=eiπ\det H = -1 = e^{i\pi}, so α=π/2\alpha = \pi/2 and e−iπ/2H=−i2(111−1)e^{-i\pi/2}H = \frac{-i}{\sqrt2}\begin{pmatrix}1&1\\1&-1\end{pmatrix}. The moduli of the entries are all 1/21/\sqrt2, so cos⁡(γ/2)=1/2\cos(\gamma/2) = 1/\sqrt2 and γ=π/2\gamma = \pi/2. The top-left entry −i/2-i/\sqrt2 has phase −π/2=−(β+δ)/2-\pi/2 = -(\beta+\delta)/2, so β+δ=π\beta+\delta = \pi; the bottom-left entry −i/2-i/\sqrt2 gives (β−δ)/2=−π/2(\beta-\delta)/2 = -\pi/2 modulo 2π2\pi, i.e. β−δ=−π\beta - \delta = -\pi. Hence β=0\beta = 0, δ=π\delta = \pi:

H=eiπ/2 RY(π/2) RZ(π).H = e^{i\pi/2}\, R_Y(\pi/2)\, R_Z(\pi).

In words: a half turn about zz, then a quarter turn about yy. Follow ∣0⟩\ket0: the half turn about zz leaves the north pole fixed, and the quarter turn about yy tips it down to the +x+x axis, which is ∣+⟩\ket+. Check numerically:

import numpy as np

def rz(a): return np.diag([np.exp(-1j * a / 2), np.exp(1j * a / 2)])
def ry(a): return np.array([[np.cos(a / 2), -np.sin(a / 2)], [np.sin(a / 2), np.cos(a / 2)]])

H = np.array([[1, 1], [1, -1]]) / np.sqrt(2)
print(np.allclose(np.exp(1j * np.pi / 2) * ry(np.pi / 2) @ rz(np.pi), H))   # True
T = np.diag([1, np.exp(1j * np.pi / 4)])
print(np.allclose(H @ T @ H, np.exp(1j * np.pi / 8) * rz(-np.pi / 2) @ ry(np.pi / 4) @ rz(np.pi / 2)))  # True

The second line shows another decomposition you will reproduce in the exercise: HTHHTH, a TT gate "seen in the xx basis", has γ=π/4\gamma = \pi/4.

What universality does and does not mean

The ZYZ theorem is an exact statement with continuous angles. Real devices offer a native gate set, and compilers translate every requested gate into it. Two further facts, stated here without proof, complete the picture. First, any single-qubit unitary can be approximated to any accuracy by finite sequences drawn from the discrete set {H,T}\{H, T\} (the Solovay–Kitaev theorem; see Nielsen and Chuang, Section 4.5 and Appendix 3). Second, single-qubit gates together with one entangling two-qubit gate such as CNOT can build any unitary on any number of qubits (Barenco et al., 1995). Universality says nothing about efficiency: most nn-qubit unitaries need a number of gates that grows exponentially in nn.

Common mistakes

  • Multiplying in circuit order. "First AA, then BB" is BABA, not ABAB.
  • Forgetting the half-angle. RZ(α)R_Z(\alpha) has entries e∓iα/2e^{\mp i\alpha/2} but rotates the Bloch sphere by the full α\alpha.
  • Treating a global phase as a different gate. P(λ)P(\lambda) and RZ(λ)R_Z(\lambda), or XZXZ and ZXZX, differ only by a global phase on a single qubit.
  • Assuming HH is a rotation about yy. HH is a half turn about the axis (x+z)/2(x+z)/\sqrt2; RY(π/2)R_Y(\pi/2) also takes ∣0⟩\ket0 to ∣+⟩\ket+, but it takes ∣+⟩\ket+ to ∣1⟩\ket1, whereas HH takes ∣+⟩\ket+ back to ∣0⟩\ket0.
  • Reading universality as efficiency. That every gate can be built says nothing about how many gates it takes.

Summary

  • Linearity plus norm preservation means gates are unitary, U†U=IU^\dagger U = I, and therefore reversible with inverse U†U^\dagger.
  • RP(α)=e−iαP/2=cos⁡α2I−isin⁡α2PR_P(\alpha) = e^{-i\alpha P/2} = \cos\frac\alpha2 I - i\sin\frac\alpha2 P; every single-qubit gate is a rotation of the Bloch sphere up to global phase.
  • Order matters: circuits are read left to right, matrices multiply right to left.
  • Every single-qubit unitary is eiαRZ(β)RY(γ)RZ(δ)e^{i\alpha}R_Z(\beta)R_Y(\gamma)R_Z(\delta).

In the exercise you build rotation gates, compute the Bloch rotation of any gate and implement the ZYZ decomposition. Next, Measurement and probability explains the one operation that is not unitary.

Exercises

Run these on your own computer. Each comes with automated checks: python -m pytest test_exercise.py. Nothing you write is sent to KetQat.

Single-qubit gates as rotations, and the ZYZ decomposition

intermediate · about 40 min · needs numpy

You will build rotation gates, check unitarity, compute the 3×33\times3 rotation that a gate applies to Bloch vectors, and decompose an arbitrary 2×22\times2 unitary into ZZ–YY–ZZ rotations.

Conventions: RP(α)=e−iαP/2=cos⁡α2I−isin⁡α2PR_P(\alpha) = e^{-i\alpha P/2} = \cos\frac\alpha2 I - i\sin\frac\alpha2 P and, for a unit axis n⃗\vec n, Rn⃗(α)=cos⁡α2I−isin⁡α2(nxX+nyY+nzZ)R_{\vec n}(\alpha) = \cos\frac\alpha2 I - i\sin\frac\alpha2 (n_x X + n_y Y + n_z Z).

Functions to implement (in starter.py)

Function Contract
rotation(axis, angle) Return Rn⃗(α)R_{\vec n}(\alpha) as a 2×22\times2 complex array. axis is any non-zero 3-vector; normalise it first.
is_unitary(U, atol=1e-10) Return True when U†U=IU^\dagger U = I within atol (entrywise).
bloch_rotation(U) Return the real 3×33\times3 matrix MM with Mij=12Tr⁡(Pi UPjU†)M_{ij} = \tfrac12\tr(P_i\,U P_j U^\dagger), P=(X,Y,Z)P = (X, Y, Z). It maps the Bloch vector of ∣ψ⟩\ket\psi to that of U∣ψ⟩U\ket\psi.
zyz_decompose(U) For a 2×22\times2 unitary, return real (alpha, beta, gamma, delta) with U=eiαRZ(β)RY(γ)RZ(δ)U = e^{i\alpha}R_Z(\beta)R_Y(\gamma)R_Z(\delta) and γ∈[0,π]\gamma\in[0,\pi].

Hint for zyz_decompose: det⁡U=e2iα\det U = e^{2i\alpha}; divide out eiαe^{i\alpha} and compare the result entry by entry with the product RZ(β)RY(γ)RZ(δ)R_Z(\beta)R_Y(\gamma)R_Z(\delta) written out in the lesson. Handle γ=0\gamma = 0 and γ=π\gamma = \pi, where only β+δ\beta+\delta or β−δ\beta-\delta is determined.

What the checks verify

  • Special cases against the lesson: RX(π)=−iXR_X(\pi) = -iX, RZ(π/2)=e−iπ/4SR_Z(\pi/2) = e^{-i\pi/4}S, and H=iRn⃗(π)H = iR_{\vec n}(\pi) with n⃗=(1,0,1)/2\vec n = (1,0,1)/\sqrt2.
  • is_unitary accepts the standard gates and random unitaries and rejects non-unitary matrices.
  • bloch_rotation returns a proper rotation (orthogonal, determinant +1+1), fixes the rotation axis, agrees with the Rodrigues rotation formula (computed independently in the test), respects composition order, and agrees with Bloch vectors computed directly from U∣ψ⟩U\ket\psi.
  • zyz_decompose reconstructs 200 seeded random unitaries and the gates I,X,Y,Z,H,S,TI, X, Y, Z, H, S, T (including the degenerate cases) to 10−910^{-9}.

Run the checks

python -m pip install numpy
python -m pytest test_exercise.py
Terminal
python -m pip install numpy

starter.py

Python
"""Single-qubit gates as rotations, and the ZYZ decomposition (KetQat Commons, Foundations)."""
import numpy as np

I2 = np.eye(2, dtype=complex)
X = np.array([[0, 1], [1, 0]], dtype=complex)
Y = np.array([[0, -1j], [1j, 0]], dtype=complex)
Z = np.array([[1, 0], [0, -1]], dtype=complex)


def rotation(axis, angle):
    """Return R_n(angle) = cos(angle/2) I - i sin(angle/2) (n . sigma) for the normalised axis n."""
    raise NotImplementedError


def is_unitary(U, atol=1e-10):
    """Return True when U^dagger U equals the identity within atol."""
    raise NotImplementedError


def bloch_rotation(U):
    """Return the real 3x3 matrix M_ij = Tr(P_i U P_j U^dagger) / 2 with P = (X, Y, Z)."""
    raise NotImplementedError


def zyz_decompose(U):
    """Return (alpha, beta, gamma, delta) with U = e^{i alpha} RZ(beta) RY(gamma) RZ(delta), gamma in [0, pi]."""
    raise NotImplementedError

test_exercise.py

Python
"""Checks for the single-qubit-rotations exercise. Run: python -m pytest test_exercise.py"""
import importlib.util
import os
from pathlib import Path

def _load_target():
    name = os.environ.get("KETQAT_COMMONS_TARGET", "starter")
    path = Path(__file__).with_name(f"{name}.py")
    spec = importlib.util.spec_from_file_location(f"{Path(__file__).parent.name}_{name}", path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module

target = _load_target()

import numpy as np
import pytest

X = np.array([[0, 1], [1, 0]], dtype=complex)
Y = np.array([[0, -1j], [1j, 0]], dtype=complex)
Z = np.array([[1, 0], [0, -1]], dtype=complex)
H = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2)
S = np.diag([1, 1j])
T = np.diag([1, np.exp(1j * np.pi / 4)])
RNG = np.random.default_rng(314)


def _rz(a):
    return np.diag([np.exp(-1j * a / 2), np.exp(1j * a / 2)])


def _ry(a):
    c, s = np.cos(a / 2), np.sin(a / 2)
    return np.array([[c, -s], [s, c]], dtype=complex)


def _random_unitary():
    m = RNG.normal(size=(2, 2)) + 1j * RNG.normal(size=(2, 2))
    q, r = np.linalg.qr(m)
    return q * (np.diag(r) / abs(np.diag(r)))


def _bloch(psi):
    return np.array([np.vdot(psi, P @ psi).real for P in (X, Y, Z)])


def test_rotation_special_cases():
    assert np.allclose(target.rotation([1, 0, 0], np.pi), -1j * X)
    assert np.allclose(target.rotation([0, 0, 1], np.pi / 2), np.exp(-1j * np.pi / 4) * S)
    assert np.allclose(target.rotation([0, 0, 5], 0.37), _rz(0.37))  # axis is normalised
    assert np.allclose(1j * target.rotation([1, 0, 1], np.pi), H)


def test_is_unitary():
    for U in (X, Y, Z, H, S, T, _random_unitary()):
        assert target.is_unitary(U)
    assert not target.is_unitary(np.array([[1, 1], [0, 1]]))
    assert not target.is_unitary(2 * H)


def test_bloch_rotation_is_a_proper_rotation_fixing_its_axis():
    for _ in range(20):
        n = RNG.normal(size=3)
        n /= np.linalg.norm(n)
        a = RNG.uniform(-np.pi, np.pi)
        M = target.bloch_rotation(target.rotation(n, a))
        assert np.allclose(M.T @ M, np.eye(3)) and np.isclose(np.linalg.det(M), 1)
        assert np.allclose(M @ n, n)
        # Rodrigues: rotation by angle a about n
        K = np.array([[0, -n[2], n[1]], [n[2], 0, -n[0]], [-n[1], n[0], 0]])
        rodrigues = np.eye(3) + np.sin(a) * K + (1 - np.cos(a)) * K @ K
        assert np.allclose(M, rodrigues)


def test_bloch_rotation_acts_on_states_and_composes_in_order():
    for _ in range(20):
        U, V = _random_unitary(), _random_unitary()
        psi = RNG.normal(size=2) + 1j * RNG.normal(size=2)
        psi /= np.linalg.norm(psi)
        assert np.allclose(target.bloch_rotation(U) @ _bloch(psi), _bloch(U @ psi))
        # circuit "V then U" is the matrix U V; its rotation is M(U) M(V)
        assert np.allclose(target.bloch_rotation(U @ V), target.bloch_rotation(U) @ target.bloch_rotation(V))
    # Hadamard swaps x and z and flips y
    assert np.allclose(target.bloch_rotation(H), [[0, 0, 1], [0, -1, 0], [1, 0, 0]])


def _rebuild(params):
    alpha, beta, gamma, delta = params
    return np.exp(1j * alpha) * _rz(beta) @ _ry(gamma) @ _rz(delta)


@pytest.mark.parametrize("name, U", [("I", np.eye(2)), ("X", X), ("Y", Y), ("Z", Z), ("H", H), ("S", S), ("T", T)])
def test_zyz_on_standard_gates(name, U):
    params = target.zyz_decompose(U)
    assert 0 <= params[2] <= np.pi + 1e-12
    assert np.allclose(_rebuild(params), U, atol=1e-9), name


def test_zyz_on_random_unitaries():
    for _ in range(200):
        U = _random_unitary()
        params = target.zyz_decompose(U)
        assert 0 <= params[2] <= np.pi + 1e-12
        assert np.allclose(_rebuild(params), U, atol=1e-9)

Check your understanding

7 questions. Pass with 70% of the points. Answers are checked on the server; retakes are allowed. Explanations appear once you pass or after three complete attempts.

  1. Which matrix cannot describe a gate on a closed single-qubit system?

    1 pt
  2. A circuit applies SS, then HH, then TT to one qubit. Which matrix maps the input state to the output state?

    1 pt
  3. What is S∣+⟩S\ket+, and how does it look on the Bloch sphere?

    1 pt
  4. Apply RY(π/3)R_Y(\pi/3) to ∣0⟩\ket0 and measure in the computational basis. What is the probability of outcome 1?

    1 pt
  5. With your zyz_decompose from the exercise, decompose U=HTHU = HTH (matrix product H @ T @ H). Enter γ\gamma in radians.

    1 pt

    Computed by running exercise “single-qubit-rotations” on your computer.

  6. Which gate undoes TT?

    1 pt
  7. Select every true statement about single-qubit gates.

    1 pt

    Select all that apply.

Sign in with GitHub to check answers and save progress. Reading stays free without an account.

References

  1. Michael A. Nielsen, Isaac L. Chuang (2010). Quantum Computation and Quantum Information (10th Anniversary Edition). Cambridge University Press. doi:10.1017/CBO9780511976667
  2. Adriano Barenco et al. (1995). Elementary gates for quantum computation. Physical Review A 52, 3457-3467. doi:10.1103/PhysRevA.52.3457