I built a functional N-qubit quantum computer simulator from scratch in Python by breaking the project down into four main challenges:
State Vector Representation: Instead of using classical bits, I represented the quantum register as a 1D NumPy array of size 2^N using np.complex128 to track complex probability amplitudes. I initialized the system to the ground state (|00...0>) by setting index 0 to 1.0 and filling the rest with zeros.
Single-Qubit Gates: Single-qubit operations (like Pauli-X and Hadamard) are 2x2 matrices, which can't be directly multiplied by a larger multi-qubit state vector. I solved this by using recursive Kronecker tensor products (np.kron) to weave the gate matrix with Identity matrices, building a massive system-wide operator matrix to update the state via np.dot.
Multi-Qubit CNOT Gate: To avoid the messy matrix math of scaling a CNOT gate when the control and target qubits aren't adjacent, I bypassed matrix multiplication entirely. I wrote a loop that converts the vector's decimal indices into binary strings, checks the control bit, flips the target bit if the control is '1', and maps the amplitude over to its new index in a buffer array.
Measurement & Collapse: To read classical data out of the superposition, I calculated the exact probabilities of each state using the absolute square of the amplitudes (np.abs(state) 2) and simulated the random choice using np.random.choice. Once an index was selected, I cleared the state vector and forced it to collapse completely onto that single winning outcome.
I tested the complete system by generating an entangled Bell State, and it successfully outputs synchronized configurations (00 or 11) every time.
Comments 2
This is amazing, have you though of using matplotlib to use a graph and analyse everything in a more graphical way?
That’s going to be my next update! Looking at raw dictionaries of qubits is a little daunting when you have more data and complexity
Sign in to join the conversation.