Page Nav

HIDE

Breaking News:

latest

Ads Place

The Magic of Quantum Computing: A Beginner’s Guide to Writing a Magic Number Guessing Game

https://ift.tt/L692Ndu Tutorial Programming a quantum computer is fun! Source: Stable Diffusion . From Classical to Quantum I’m not s...

https://ift.tt/L692Ndu

Tutorial

Programming a quantum computer is fun!

Source: Stable Diffusion.

From Classical to Quantum

I’m not sure exactly what it is about quantum computing that brings such a sense of amazement and intrigue, but it definitely feels refreshingly different than programming a classical computer. The field of quantum computing is still young and filled with potential, opening the door to many possibilities for individuals, just like you, to make an impact.

I’ve often found that one of the best ways to learn about a technology is through games. What better way to learn about quantum computing than to write your own game?

The Design of a Simple Game

We’re going to use Python and the open-source quantum computing library called Qiskit, to write a Magic Number Guessing game.

Our game is very simple, but will be powered by the properties of quantum computing.

Our game will have the following design:

  1. The quantum computer will generate a random number from 0 to 15.
  2. The player will have to guess the number.
  3. At each round, we’ll tell the player if they are too low or too high.

What a fantastic way to get started with quantum computing programming!

Let’s get started!

The Fun of Quantum Computing

Often, when we think about quantum computing, one of the first topics that come to mind is the idea of bits being represented simultaneously as zero and one. This is a behavior of microscopic particles that we call superposition.

Just imagine it. At the microscopic level, the entire world behaves in a completely different manner that we’re used to. Particles spin and exist in multiple states. Sometimes, they may even pop in and out of existence. They can even travel through physical walls; a behavior called quantum tunneling!

And yet, we can harness these amazing effects by programming a quantum computer.

Since one of the most powerful properties of quantum computing is the idea of representing a bit of information simultaneously as both a zero and a one, it’s one of the first logical gates that beginners learn about when building their first quantum circuit.

When a Bit is a Qubit

A bit on a classical computer can hold a value of zero or one, but certainly not both at the same time. However, a qubit on a quantum computer can hold a value of both zero and one at the same time, enabling superposition, until measured.

We will use the powerful effect of superposition as the core piece to our game.

On a quantum computer, the Hadamard gate is used to place a qubit into superposition. When this is done, we can measure the qubit and receive back a random value of zero or one. That is, half of the time when we measure the qubit we will receive a result of zero, while the other half of the time we will receive a value of one.

Since a qubit has a 50/50 chance of measuring either a zero or a one, we can use this effect to randomly generate a bit.

Generating Random Numbers

Now that we know that we can use the Hadamard gate to create a random number of zero or one on a quantum computer, let’s extend this idea to four qubits. This gives us the ability to generate four random bits, which when converted to an integer, results in a value from 0 to 15.

This capability for generating random numbers within a specific range will be used as a key part for our game.

Generating a Random Number on a Classical Computer

Before diving into the quantum computing part, let’s first see how to generate some random numbers on a classical computer. This will allow us to compare the results of the random numbers generated on a classical computer to those on a quantum computer.

Using Python, we can generate pseudo-random numbers quite easily using the following example code.

import random
for i in range(10):
num = random.randint(0, 15)

The above code generates a random number from 0 to 15, resulting in the following array of values: [14, 7, 14, 10, 11, 6, 11, 10, 1, 9].

If we draw a histogram of 300 random numbers generated from this method, we can see the graph displayed below.

The distribution of 300 random numbers generated with the Python random() module. Source: Author.

Notice, how each number occurs relatively equal in comparison to the others.

This seems to be pretty random!

Generating a Random Number from Superposition

Let’s take this into the quantum world.

Just as we’ve done with the classical computer method, now we’re going to use superposition with four qubits in order to generate four random bits that we can use to represent a number from 0 to 15.

We can use the following code below.

from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, execute, Aer
from qiskit.visualization import plot_histogram

# Setup a quantum circuit (4 bit random number 0–15).
qc = QuantumCircuit(4)

# Select the simulator.
simulator = Aer.get_backend(‘aer_simulator’)

# Place all qubits into superposition (50% chance 0 or 1).
qc.h(range(4))

# Measure each qubit.
qc.measure_all()

The above example creates a quantum circuit using the Hadamard gate on each qubit to place them into superposition. We then measure the qubits to read the random values of zero or one for each.

Here is what the quantum circuit looks like when we draw it.

A quantum computing circuit for generating a 4-bit random number using superposition and the Hadamard gate. Source: Author, generated by Qiskit.

As you can see, we’re simply using an H-gate on each qubit and measuring the resulting value.

You’re probably wondering how the results compare to the classical method before? As it turns out, this method does indeed generate random numbers, as shown in the following array: [8, 11, 4, 2, 13, 9, 7, 12, 15, 13].

We can draw a histogram of the random numbers to confirm the distribution of random values.

The distribution of 300 random numbers generated with superposition. Source: Author.

Just like the classical computing method, this too, seems to be quite random!

Generating a Random Number from Quantum Noise

Using superposition to generate random numbers is easy enough. It’s simple and straight-forward.

However, we can also generate random numbers on a quantum computer by using the property of quantum noise.

When a quantum gate is executed, there is a tiny bit of noise (or error) that can effect the gate. It’s this tiny amount of noise that we can harness to generate random numbers.

Luckily, the Qiskit library makes it easy to take advantage of quantum noise. There have even been other projects that use this very feature for random number generation.

Below is an example of setting up a quantum circuit to take advantage of noise.

from qiskit.providers.aer.noise import NoiseModel, pauli_error

# Initialize bit-flip error rates.
reset_value = 0.03
measure_value = 0.1
gate_value = 0.05

# Initialize QuantumError on the X and I gates.
reset_error_rate = pauli_error([('X', reset_value), ('I', 1 - reset_value)])
measure_error_rate = pauli_error([('X',measure_value), ('I', 1 - measure_value)])
gate1_error_rate = pauli_error([('X',gate_value), ('I', 1 - gate_value)])
gate2_error_rate = gate1_error_rate.tensor(gate1_error_rate)

# Add errors to a noise model.
noise_model = NoiseModel()
noise_model.add_all_qubit_quantum_error(reset_error_rate, "reset")
noise_model.add_all_qubit_quantum_error(measure_error_rate, "measure")
noise_model.add_all_qubit_quantum_error(gate1_error_rate, ["u1", "u2", "u3"])
noise_model.add_all_qubit_quantum_error(gate2_error_rate, ["cx"])

The above code initializes quantum noise for the various gates that we will be using in our program.

Once we have the noise ready, we can create a quantum circuit to generate random numbers from noise by using the following code below.

from qiskit.providers.aer import QasmSimulator

# Setup a quantum circuit (4 bit random number 0–15).
qc = QuantumCircuit(4)
simulator = QasmSimulator()

# Setup quantum circuit for noise generation to build a random value.
for i in range(50):
qc.u(0,0,0,0)
qc.u(0,0,0,1)
qc.u(0,0,0,2)
qc.u(0,0,0,3)
qc.cx(0,1)
qc.cx(1,2)
qc.cx(0,2)
qc.cx(0,3)
qc.cx(1,3)
qc.cx(2,3)
qc.barrier()

qc.measure_all()

The above code creates a quantum circuit as shown below.

A quantum computing circuit for generating a 4-bit random number using quantum noise. Source: Author, generated by Qiskit.

Notice that we’re using the U-Gate combined with a controlled-not (CX) gate in order to generate the required noise.

You may have noticed the for-loop in the quantum circuit. We need to run the circuit a number of times in order to magnify the noise that is generated. Otherwise, our random numbers will be heavily skewed towards a zero or one, rather than randomly distributed. It’s important to balance the iterations of the loop versus the randomness of the numbers, as the longer the circuit, the longer it will take to run.

Finally, we measure the resulting four qubits to obtain random values.

Once again, the resulting output, indeed, appears quite random, as shown in the following array: [4, 0, 6, 9, 2, 9, 15, 5, 2, 12].

The distribution of 300 random numbers generated using quantum noise. Source: Author.

Creating the Magic Number Game

Now that we’re ready to implement the game, we need to choose a method for generating the random numbers that will be used.

Both quantum computing approaches (superposition and noise) would equally suffice.

The superposition method is more commonly used for generating randomness, as it uses a simpler circuit, while the noise method takes advantage of distinct qualities of quantum computing gates. In fact, each technique can be equally interchangeable.

However, let’s move forward with the method of using quantum noise, a more unique approach, and implement this in our game.

Wrapping quantum into a classical function

To keep things tidy, we’ll wrap our noisy quantum circuit into a Python method called random_number. We can call this method to choose our magic number for the player to guess.

def random_number():
# Setup a quantum circuit.
qc = QuantumCircuit(4)
simulator = QasmSimulator()

# Setup quantum circuit for noise generation to build a random value with greater iteration.
for i in range(50):
qc.u(0,0,0,0)
qc.u(0,0,0,1)
qc.u(0,0,0,2)
qc.u(0,0,0,3)
qc.cx(0,1)
qc.cx(1,2)
qc.cx(0,2)
qc.cx(0,3)
qc.cx(1,3)
qc.cx(2,3)
qc.barrier()

qc.measure_all()

# Execute the circuit.
job = execute(qc, simulator, basis_gates=noise_model.basis_gates, noise_model=noise_model, shots=1)
result = job.result()
counts = result_bit_flip.get_counts(0)

num=list(counts.keys())[0]
return int(num, 2)

Once we have a magic number generated, we start a game loop. At each round, we’ll ask the user to input a guess from 0 to 15 and tell the player if their guess is too low or too high.

The code for the game is shown below.

# Generate a random quantum number.
magic_number = random_number()

guess = -999
count = 0
while guess != magic_number and guess != -1:
count = count + 1
guess = int(input("Guess a number from 0 to 15? "))
if guess < magic_number:
print("Too low!")
elif guess > magic_number:
print("Too high!")
else:
print("Great guess! You won in", count, "guesses!")
break

That’s really all there is to it!

Lights, Camera, Action!

As you can see, our game is very simple in nature. However, the game demonstrates the capability of a quantum computer to generate a random number, which is, of course, a key part to this game.

There is amazing potential to expand on this idea much further. Imagine the possibilities for adding graphics, game mechanics, event 3D or virtual reality effects into a game — all powered with quantum computing.

The simple act of generating a quantum random number can power the key pieces behind your game design.

Give Me Speed

Now, it is important to note, there is a consideration with regard to speed of execution on a quantum computer. After all, processing a quantum circuit on a simulator or physical quantum computer (such as IBM Quantum) may require significant processing time and delays.

For now, however, games can still serve as an excellent proof of concept and learning opportunity. In addition, quantum simulators and hardware are improving every year.

So stick with it and learn all that you can!

Excited Yet?

I hope that you’re as excited as I am about quantum computing and its potential application to a vast array of computer problems.

Now that you’ve learned how to use the Python Qiskit quantum computing library, along with superposition or quantum noise, you can easily generate random numbers for a multitude of purposes.

Of course, the fun of quantum computing goes well beyond random numbers. There are an ever-growing volume of quantum algorithms that take full advantage of the quantum process.

This is only the tip of the iceberg!

The Future is Wide Open

Now that you know how to create random numbers with quantum computing, it’s time to make your own applications and games!

You can download the complete code example for the Magic Number Guessing game here.

About the Author

If you’ve enjoyed this article, please consider following me on Medium, Twitter, and my web site to be notified of my future posts and research work.


The Magic of Quantum Computing: A Beginner’s Guide to Writing a Magic Number Guessing Game was originally published in Towards Data Science on Medium, where people are continuing the conversation by highlighting and responding to this story.


from Towards Data Science - Medium
https://towardsdatascience.com/the-magic-of-quantum-computing-a-beginners-guide-to-writing-a-magic-number-guessing-game-c1cdb384f457?source=rss----7f60cf5620c9---4
via RiYo Analytics

No comments

Latest Articles