Simple Quantum Computing In 150 Lines Of Python

What does it take to build a quantum computer? Lots of exotic supercooled hardware. However, creating a simulator isn’t nearly as hard and can give you a lot of insight into how this kind of computing works. A simulator doesn’t even have to be complicated. Here’s one that exists in about 150 lines of Python code.

You might wonder what the value is. After all, there are plenty of well-done simulators including Quirk that we have looked at in the past. What’s charming about this simulator is that with only 150 lines of code, you can reasonably read the whole thing in a sitting and gain an understanding of how the different operations really affect the state.

One thing to note is that the 150 lines quoted includes comments, so the actual code bulk is even less. The majority of the program handles the quantum register and a generic way to apply a matrix to the quantum state. That leaves most of the operations as just simple definitions of matrices. For example:

 # Hadamard Gate
 'H': np.multiply(1. / np.sqrt(2), np.matrix([
 [1, 1],
 [1, -1]
 ])),

Using the simulator involves writing more Python code, so really this is a library more than a simulator like Quirk. For example, here’s part of the example code included:

#############################################
# Swap 2 Qubits #
#############################################
# Here, We Will Apply a Pauli-X Gate / NOT Gate
# To the first qubit, and then after the algorithm,
# it will be swapped to the second qubit.

Swap = QuantumRegister(2) # New Quantum Register of 2 qubits
Swap.applyGate('X', 1) # Apply The NOT Gate. If Measured Now, it should be 10

# Start the swap algorithm
Swap.applyGate('CNOT', 1, 2)
Swap.applyGate('H', 1)
Swap.applyGate('H', 2)
Swap.applyGate('CNOT', 1, 2)
Swap.applyGate('H', 1)
Swap.applyGate('H', 2)
Swap.applyGate('CNOT', 1, 2)
# End the swap algorithm

print('SWAP: |' + Swap.measure() + '>') # Measure the State, Should be 01

If you want to learn more about quantum computing, we did a series recently that started simply, looked at communications, and wrapped up with a look at Grover’s algorithm.

11 thoughts on “Simple Quantum Computing In 150 Lines Of Python

        1. You can’t be sure if you’ve scored until someone observes it. You must upload video so strangers on the internet can observe. It’s an example of Schrödinger’s “cat”.

          1. Well it doesn’t help much. How can you be sure someone observed it, unless someone else observed someone observe it? And how can you be sure that someone else really did observe … ah, crap. It’s turtles all the way down.

Leave a Reply

Please be kind and respectful to help make the comments section excellent. (Comment Policy)

This site uses Akismet to reduce spam. Learn how your comment data is processed.