Tutorial: Getting started with Quantum Computing in Python

Published Categorised as Python, Quantum Computing, Tutorial Tagged , , ,

Quantum computers might sound a bit exotic and far into the future, but in reality, they are now accessible in the cloud or through emulators for everyone to write quantum code. In this tutorial, we’ll go through how you can program a simple quantum computer to generate random numbers.

This is part one of the tutorial series on quantum computing in Python and introduces the fundamentals to quantum programming.
Overview of the DataEspresso tutorial series on quantum computing.

This example can be done on any emulator or quantum computer. For this blog post, the free and open source Python library ProjectQ is used.
ProjectQ can emulate a quantum computer on any CPU, or connect to IBMs quantum computer as a backend.
To get started, just install ProjectQ through pip or follow their installation guide

pip install projectq

Programming a quantum computer

Programming a quantum program is a bit different from what we are used to when creating classical programs, we have to dive down in the levels of computer abstractions and use logic gates to manipulate data, along the same mindset Alan Turing used when creating his famous Turing Machine, which describes a classical machine doing classical computations on classical bits.
A Quantum Turing machine describes a computer that can perform quantum computations on a Qubit, where quantum computations refers to applying quantum logic gates such as Pauli-X, CNOT etc to Qubits.
This means that any program possible to write on a classical computer is possible to run on a quantum computer, and vice versa, but this doesn’t mean any program will be more effective on a quantum computer, in fact, a range of programs will run slower on a quantum computer and a quantum computer will have to work in parallel with a classical computer to handle computations where the classical computer falls short, computations such as matrix multiplication or finding prime factors to break cryptography.

Creating a random generator with quantum gates

Creating a (pseudo) random number is one of the first things taught in computer science courses. Usually, it involves importing a pre-made library called something along the lines of ‘Random’ and then just call the appropriate function.
In quantum computing we’re not yet at this level of abstraction, but to create a random number is almost as easy by using quantum logic gates.

Quantum gates are similar to the logic gates we know from classical computing. Eg AND, OR, NAND, XOR etc
For those not familiar with the concept, logic gates are a set of input and output used to manipulate an input through boolean functions.
For example, if we feed the OR gate two numbers where one or both is one, the output will be True, if we feed the input two zeros the output will be false.

ABQ
000
011
101
111

The table above shows the truth table of an OR gate, where A and B are inputs and Q is the output. Imagine that a door only opens when a lamp is lit and will stay closed when both lamps are turned off.

Logic gates can be used to compute any operation, and in quantum computing, we can use the logic gate called Hadamard to create a random number (1 or 0).
The Hadamard gate takes one input, and maps the output with a equal probability of being 1 or 0, i.e. create a superposition where the input can be either 1 or 0 at the same time.

The basis state |0⟩ is mapped to: $$\frac{|0\rangle + |1\rangle}{\sqrt{2}}$$

The basis state |1⟩ is mapped to: $$\frac{|0\rangle – |1\rangle}{\sqrt{2}}$$


The Hadamard gate is represented by the Hadamard matrix which shows that the rows are mutually orthogonal.

$$ H = \frac{1}{\sqrt{2}} \begin{bmatrix}1 & 1 \\\ 1 & -1\end{bmatrix}$$

Read more about the Hadamard matrix and other Quantum Logic gates on Wikipedia

Essentially, the Hadamard gate flips a coin and while the coin is in the air, it’s in a superposition in the sense that the coin can be both head and tail until it falls back down and we glance down at it – the human way of measuring the state of the coin.

Our quantum random generator outlined in a few simple steps together with the coin analogy

  1. Create a new Qubit
    • Fishing a coin out of our pocket
  2. Applying a Hadamard gate to the Qubit to put it into a superposition of equal probability of being 0 and 1.
    • Tossing our coin in the air, it can now be either heads or tail.
  3. Measuring the Qubit
    • The coin has finally landed and settled, its time to look at it to see if its head or tail.

Start by importing projectQ along with the Hadamard gate and the measuring function. We’re using projectQ in this tutorial, but the same approach can be followed in other libraries and systems as well, the code syntax will be a bit different, but the theory will be the same.

from projectq.ops import H, Measure
from projectq import MainEngine

Initialise the backend, we’re using the emulator, but you can also use eg IBMs quantum computer.
Then Create a new Qubit to apply computations on.

quantum_engine = MainEngine()
qubit = quantum_engine.allocate_qubit()

We now have a Qubit that initialised and ready to be turned into superposition. Remeber the coin analogy here, where we picked up a coin and now is ready to throw it in the air.

We’re then applying the Hadamard gate to the Qubit, this refers to the step where we toss the coin up in the air.
The syntax to do this will vary between each library and tool but in ProjectQ it’s simply done in the following way.

H | qubit

One interesting thing to pay attention to here is that we’re applying the gate directly to the Qubit and not creating a copy. This is because unlike classical bits, Qubits cannot be copied due to fundamental laws of physics.
However, its possible to teleport a quantum state from one location to another, but this is something for the next tutorial.

With the Qubit in a superposition, we can now measure it, this refers to the step where the coin has landed and settled on the table and its time to have a look whether its head or tail.
In projectQ the measuring is done with the following command.

Measure | qubit

The measured qubit can now be printed and will return either 0 or 1.

print(int(qubit))

Tidying this all up in a complete Python code along with a for loop that demonstrates the randomness of our coin toss.

def get_random_number(quantum_engine):
    qubit = quantum_engine.allocate_qubit()
    H | qubit
    Measure | qubit
    random_number = int(qubit)
    return random_number

# This list is used to store our random numbers
random_numbers_list = []
# initialises a new quantum backend
quantum_engine = MainEngine()
# for loop to generate 10 random numbers
for i in range(10):
    # calling the random number function and append the return to the list
    random_numbers_list.append(get_random_number(quantum_engine))
# Flushes the quantum engine from memory
quantum_engine.flush()
print('Random numbers', random_numbers_list)

Some outputs from the random generator.

Run 1: Random numbers [1, 1, 1, 1, 1, 0, 0, 1, 0, 0]

Run 2: Random numbers [0, 0, 1, 0, 0, 0, 1, 0, 0, 1]

Run 3: Random numbers [0, 1, 1, 0, 1, 0, 1, 0, 1, 1]

Run 4: Random numbers [1, 0, 1, 1, 0, 0, 1, 1, 0, 0]

Run 5: Random numbers [1, 1, 1, 1, 1, 1, 0, 1, 1, 0]

This was a simple introduction to creating a random generator with quantum gates in Python. Feel free to post any comments, concerns or questions in the comment field below.

By Christopher Ottesen

Chris is a data scientist based in London, UK.

19 comments

    1. Thank you Shrini, I’m delighted that you enjoyed the read.
      The next tutorial should be done within the next few days!

    1. Thank you Sajad, I’m delighted that you enjoyed the read.
      The next tutorial should be done within the next few days!

  1. since this is using an emulator, i assume it is really still a pseudo random number under the hood? what practical uses will this type of computing have for freelance programmers?

    1. Yeah, you’re right, these values are obtained by simulating the quantum algorithm classically. By changing a few lines of code, the program can run an actual quantum random number generator using the IBM Quantum Experience as the back-end. I don’t think the quantum machines will replace our classical machines anytime soon, but instead handle the tougher computations just like Intel’s 8080 co-processors for float numbers a few years ago. This said, the term ‘Freelance programmers’ is quite wide, and I do see benefits for programmers within for example machine learning, or other fields where a lot of matrix multiplications or simulations are undertaken, and not to mention quantum cryptography which has to be in place to keep the internet secure as soon as we reach machines with a sensible number of qubits.

  2. Thanks for the explanation.
    Can you inform us how are the random numbers genearted mathematically using Hadamard and measuring gates ?

Leave a comment

Your email address will not be published. Required fields are marked *