Curriculum / Real-World Quantum Python / State Vector Simulation

Lesson 3 of 20Code challengePro+150 XP

State Vector Simulation

Build a complete state vector simulator in Python, understand exactly what happens inside quantum hardware simulators.

State Vector Simulation

Before running on real hardware, quantum programs run on classical simulators. The most faithful simulator is a state vector simulator, it stores the full quantum state as a vector of complex amplitudes and applies each gate as a matrix multiplication. Writing one yourself is the single best way to understand what actually happens inside Qiskit's Aer, Cirq's simulators, or any other framework. There are no mysteries left once you can draw the data structure on a napkin.

State Vector Representation

An n-qubit pure state is a vector of complex amplitudes, one per computational-basis string. For 3 qubits:

|ψ⟩ = α₀₀₀|000⟩ + α₀₀₁|001⟩ + α₀₁₀|010⟩ + α₀₁₁|011⟩ + α₁₀₀|100⟩ + α₁₀₁|101⟩ + α₁₁₀|110⟩ + α₁₁₁|111⟩

Stored in memory as a Python list (or NumPy array) of 2³ = 8 complex numbers:

state = [α₀₀₀, α₀₀₁, α₀₁₀, α₀₁₁, α₁₀₀, α₁₀₁, α₁₁₀, α₁₁₁]

The normalisation constraint Σ|αᵢ|² = 1 must hold after every operation. The measurement probability of basis state |i⟩ is simply |αᵢ|². Sampling is just a weighted draw from these probabilities.

This already tells you why exact simulation does not scale: 30 qubits needs 2³⁰ ≈ 10⁹ complex numbers (16 GB at double precision). 50 qubits needs 2⁵⁰ ≈ 10¹⁵ amplitudes, no classical computer can store that. This is the wall that quantum hardware is built to climb over.

Gate Application, The Efficient Way

A naive textbook simulator builds the full 2ⁿ × 2ⁿ matrix (I ⊗ ... ⊗ G ⊗ ... ⊗ I) and multiplies. That is terrible: memory scales as 4ⁿ and most of the entries are zero.

The trick: a single-qubit gate G on qubit k only mixes pairs of amplitudes that differ in the k-th bit. For each basis index i where bit k is 0, find the partner index j = i XOR (1 << k), and apply the 2×2 matrix to the pair (state[i], state[j]):

This is the opening of the lesson. The full walkthrough, the interactive circuit, and the graded challenge continue inside myqubit.

How this lesson works

A hands-on coding challenge. You write Qiskit-compatible Python in the browser editor, run it instantly via WebAssembly, watch the circuit and Bloch sphere react, and pass automatic output checks. The AI tutor Qubitus gives Socratic hints if you get stuck.

Part of: Real-World Quantum Python

Write production-quality quantum Python, circuit optimization, hybrid algorithms, cloud backends, noise modeling, and software engineering patterns.

This lesson is part of Pro

Unlock Real-World Quantum Python and all 10 tracks with Pro: $12.99/month, $79/year, or $97 lifetime. Start with the free track first if you are new.