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

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

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

Tutorial

Programming a quantum computer is fun!

Source: Stable Diffusion.

I’m undecided exactly what it’s about quantum computing that brings such a way of amazement and intrigue, but it surely definitely feels refreshingly different than programming a classical computer. The sector of quantum computing continues to be young and stuffed with potential, opening the door to many possibilities for people, similar to you, to make an impact.

I’ve often found that probably the greatest ways to find out about a technology is thru games. What higher technique to find out about quantum computing than to jot down your individual game?

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

Our game may be very easy, but will probably be powered by the properties of quantum computing.

Our game may have the next design:

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

What a implausible technique to start with quantum computing programming!

Let’s start!

Often, after we take into consideration quantum computing, one in every of the primary topics that come to mind is the thought of bits being represented concurrently as zero and one. It is a behavior of microscopic particles that we call superposition.

Just imagine it. On the microscopic level, the whole world behaves in a totally different manner that we’re used to. Particles spin and exist in multiple states. Sometimes, they could even pop out and in of existence. They will even travel through physical partitions; a behavior called quantum tunneling!

And yet, we are able to harness these amazing effects by programming a quantum computer.

Since probably the most powerful properties of quantum computing is the thought of representing a bit of knowledge concurrently as each a zero and a one, it’s one in every of the primary logical gates that beginners find out about when constructing their first quantum circuit.

A bit on a classical computer can hold a price of zero or one, but definitely not each at the identical time. Nevertheless, a qubit on a quantum computer can hold a price of each zero and one at the identical time, enabling superposition, until measured.

We’ll use the powerful effect of superposition because the core piece to our game.

On a quantum computer, the Hadamard gate is used to position a qubit into superposition. When this is finished, we are able to measure the qubit and receive back a random value of zero or one. That’s, half of the time after we measure the qubit we are going to receive a results of zero, while the opposite half of the time we are going to receive a price of 1.

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

Now that we all know that we are able to use the Hadamard gate to create a random variety of zero or one on a quantum computer, let’s extend this concept to 4 qubits. This offers us the flexibility to generate 4 random bits, which when converted to an integer, ends in a price from 0 to fifteen.

This capability for generating random numbers inside a particular range will probably be used as a key part for our game.

Before diving into the quantum computing part, let’s first see the best way to generate some random numbers on a classical computer. This may allow us to match the outcomes of the random numbers generated on a classical computer to those on a quantum computer.

Using Python, we are able to generate pseudo-random numbers quite easily using the next example code.

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

The above code generates a random number from 0 to fifteen, leading to the next 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 are able to see the graph displayed below.

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

Notice, how each number occurs relatively equal as compared to the others.

This appears to be pretty random!

Let’s take this into the quantum world.

Just as we’ve done with the classical computer method, now we’re going to make use of superposition with 4 qubits in an effort to generate 4 random bits that we are able to use to represent a number from 0 to fifteen.

We will use the next 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% likelihood 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 position them into superposition. We then measure the qubits to read the random values of zero or one for every.

Here’s what the quantum circuit looks like after we draw it.

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

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

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

We will draw a histogram of the random numbers to verify the distribution of random values.

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

Similar to the classical computing method, this too, appears to be quite random!

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

Nevertheless, we may also generate random numbers on a quantum computer through the use of the property of quantum noise.

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

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

Below is an example of establishing a quantum circuit to make the most 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 assorted gates that we will probably be using in our program.

Once we’ve got the noise ready, we are able to create a quantum circuit to generate random numbers from noise through the use of the next 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 construct 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: Writer, generated by Qiskit.

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

You will have noticed the for-loop within the quantum circuit. We’d like to run the circuit plenty of times in an effort to magnify the noise that’s generated. Otherwise, our random numbers will probably be heavily skewed towards a zero or one, fairly than randomly distributed. It’s essential to balance the iterations of the loop versus the randomness of the numbers, because the longer the circuit, the longer it is going to take to run.

Finally, we measure the resulting 4 qubits to acquire random values.

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

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

Now that we’re able to implement the sport, we want to decide on a technique for generating the random numbers that will probably be used.

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

The superposition method is more commonly used for generating randomness, because it uses an easier circuit, while the noise method takes advantage of distinct qualities of quantum computing gates. Actually, each technique may be equally interchangeable.

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

To maintain things tidy, we’ll wrap our noisy quantum circuit right into a Python method called random_number. We will call this method to decide on 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 construct 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’ve got a magic number generated, we start a game loop. At each round, we’ll ask the user to input a guess from 0 to fifteen and tell the player if their guess is just too low or too high.

The code for the sport 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 fifteen? "))
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 may be to it!

As you’ll be able to see, our game may be very easy in nature. Nevertheless, the sport demonstrates the aptitude of a quantum computer to generate a random number, which is, in fact, a key part to this game.

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

The easy act of generating a quantum random number can power the important thing pieces behind your game design.

Now, it is necessary to notice, there may be a consideration with regard to hurry of execution on a quantum computer. In spite of everything, processing a quantum circuit on a simulator or physical quantum computer (akin to IBM Quantum) may require significant processing time and delays.

For now, nonetheless, games can still function a wonderful proof of concept and learning opportunity. As well as, quantum simulators and hardware are improving every 12 months.

So stick to it and learn all which you can!

I hope that you simply’re as excited as I’m about quantum computing and its potential application to an enormous array of computer problems.

Now that you simply’ve learned the best way to use the Python Qiskit quantum computing library, together with superposition or quantum noise, you’ll be able to easily generate random numbers for a mess of purposes.

In fact, 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 just the tip of the iceberg!

Now that the best way to create random numbers with quantum computing, it’s time to make your individual applications and games!

You’ll be able to download the whole code example for the Magic Number Guessing game here.

When you’ve enjoyed this text, please consider following me on Medium, Twitter, and my website to be notified of my future posts and research work.

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here