# The quantum (a)muse(ment) #2: mastering random numbers generation

*Is it possible to design a quantum circuit to generate random numbers in custom intervals?*

Writing code for Vera Molnar-like generative art, I wanted to generate numbers in a certain range so I found myself asking: “can we shape number generation directly in the quantum circuit, instead of drawing numbers out of a uniform distribution and discarding those which are out-of-interval?”

Actually, this is possible by designing ad-hoc quantum circuits by applying certain operations on qubits.

Let’s say that we want to generate a random number in interval [0,3].

We can achieve this by initializing 2 qubits and inducing superposition with Hadamard:

Now let’s say that we want to generate numbers in [2,3]. We have to apply NOT to q1 (pi rotation on X axis):

It’s easier to understand what is happening here if we plot Bloch sphere for each qubit:

Leftmost qubit is always going to collapse to 1 while the other is going to collapse to 0 with probability ½ or to 1 with probability ½.

This leads to:

**1***0*,**1***1*

So we prepare one qubit with ket(0) and obtain ket(1) by applying NOT operator and make other one random by applying Hadamard.

And this quickly generalizes to higher numbers, too!

# Amusement #1: even numbers only

Let’s take a look to even numbers “pattern”:

*00***0**,*01***0**,*10***0**,*11***0**

The figure in the rightmost position should be zero, while the other two positions should collapse half the times to 0 and the other half to 1.

So we have to “prepare” the rightmost qubit and leave it to ket(0) while applying Hadamard to the other qubits, so that they can collapse with probability ½ to 0 or 1.

# Amusement #2: odd numbers only

In this case, last qubit should be prepared to always collapse to 1 while the others are going to collapse to 1 or 0 with probability ½.