Quantum Circuit Lab / math engine
Lesson 05 · math engine

The Linear Algebra of a Qubit with NumPy

Build the vector and matrix operations behind a qubit with NumPy, using code instead of unexplained quantum notation.

Intermediate16–18 min readsoftware engineering · quantum computing

Vectors are the state

Choose a basis order—usually |0⟩, |1⟩—and represent a qubit as a length-two complex vector.

import numpy as np

zero = np.array([1, 0], dtype=complex)
one  = np.array([0, 1], dtype=complex)

assert np.vdot(zero, zero) == 1
assert np.vdot(zero, one) == 0

The conjugate dot product matters because amplitudes can be complex. A matrix is a gate, and applying it is simply U @ state.

X = np.array([[0, 1], [1, 0]], dtype=complex)
H = np.array([[1, 1], [1, -1]], dtype=complex) / np.sqrt(2)
state = H @ zero
print(np.round(state, 3))  # [0.707+0.j 0.707+0.j]

Expectation values

For an observable A, the expectation value is ⟨ψ|A|ψ⟩. It is the average obtained by repeating the same experiment many times.

Z = np.array([[1, 0], [0, -1]], dtype=complex)
expectation = np.vdot(state, Z @ state).real
print(expectation)  # 0.0 for |+>
Implementation habit: add a norm check after every gate. A drifting norm usually means an indexing or complex-multiplication bug.

Next inspect how amplitudes become probabilities, then learn why a simulator avoids enormous full matrices.