Quickstart: Implement a Quantum Random Number Generator in Q#

A simple example of a quantum algorithm written in Q# is a quantum random number generator. This algorithm leverages the nature of quantum mechanics to produce a random number.


Write a Q# operation

Q# operation code

  1. Replace the contents of the Operation.qs file with the following code:
namespace Qrng {
    open Microsoft.Quantum.Intrinsic;

    operation SampleQuantumRandomNumberGenerator() : Result {
        using (q = Qubit())  { // Allocate a qubit.
            H(q);             // Put the qubit to superposition. It now has a 50% chance of being 0 or 1.
            let r = M(q);     // Measure the qubit value.
            return r;

As mentioned in our What is Quantum Computing? article, a qubit is a unit of quantum information that can be in superposition. When measured, a qubit can only be either 0 or 1. However, during execution the state of the qubit represents the probability of reading either a 0 or a 1 with a measurement. This probabilistic state is known as superposition. We can use this probability to generate random numbers.

In our Q# operation, we introduce the Qubit datatype, native to Q#. We can only allocate a Qubit with a using statement. When it gets allocated, a qubit is always in the Zero state.

Using the H operation, we are able to put our Qubit in superposition. To measure a qubit and read its value, you use the M intrinsic operation.

By putting our Qubit in superposition and measuring it, our result will be a different value each time the code is invoked.

When a Qubit is de-allocated it must be explicitly set back to the Zero state, otherwise the simulator will report a runtime error. An easy way to achieve this is invoking Reset.

Visualizing the code with the Bloch sphere

In the Bloch sphere, the north pole represents the classical value 0 and the south pole represents the classical value 1. Any superposition can be represented by a point on the sphere (represented by an arrow). The closer the end of the arrow to a pole the higher the probability the qubit collapses into the classical value assigned to that pole when measured. For example, the qubit state represented by the red arrow below has a higher probability of giving the value 0 if we measure it.

A qubit state with a high probability of measuring zero

We can use this representation to visualize what the code is doing:

  • First we start with a qubit initialized in the state 0 and apply H to create a superposition in which the probabilities for 0 and 1 are the same.
Preparing a qubit in superposition
  • Then we measure the qubit and save the output:
Measuring a qubit and saving the output

Since the outcome of the measurement is completely random, we have obtained a random bit. We can call this operation several times to create integers. For example, if we call the operation three times to obtain three random bits, we can build random 3-bit numbers (that is, a random number between 0 and 7).

Creating a complete random number generator using a host program

Now that we have a Q# operation that generates random bits, we can use it to build a complete quantum random number generator with a host program.

To run your new Q# program from Python, save the following code as host.py:

import qsharp
from Qrng import SampleQuantumRandomNumberGenerator # We import the 
# quantum operation from the namespace defined in the file Qrng.qs
max = 50 # Here we set the maximum of our range
output = max + 1 # Variable to store the output
while output > max:
    bit_string = [] # We initialise a list to store the bits that
    # will define our random integer
    for i in range(0, max.bit_length()): # We need to call the quantum
        # operation as many times as bits are needed to define the
        # maximum of our range. For example, if max=7 we need 3 bits
        # to generate all the numbers from 0 to 7. 
        # Here we call the quantum operation and store the random bit
        # in the list
    output = int("".join(str(x) for x in bit_string), 2) 
# Transform bit string to integer

print("The random number generated is " + str(output))
# We print the random number

You can then run your Python host program from the command line:

$ python host.py
Preparing Q# environment...
..The random number generated is 42