Qiskit: Coin Tossing

In previous chapter, you have already learned about running Quantum Programs by using Quantum Simulators such as Qiskit Aer Simulator. In this chapter, you will create your a Quantum Program to generate a random number from 0 and 1, the equivalent to tossing a coin.

This program is commonly referred to as the “Hello World” of Quantum Computing. While it may not look like much, this program will do that no Classical Computer can do- generating a Random Number. This is because all the algorithms for generating a random number on a classical computer are deterministic. However, this will only be true when running this Quantum Program on an actual Quantum Computer and not a simulator, which we will do in one of the coming chapters.


Quantum Coin Tossing Program

We will first create a Quantum Program for the equivalent of tossing a coin, and then run the experiments a certain number of times and measure the outputs.

Creating the Quantum Program

We will first create a Quantum Circuit with 1 Qubit and 1 bit.

# Creating a Quantum Circuit with 1 Qubit and 1 bit
qc = QuantumCircuit(1, 1)

Next, we apply the Hadamard Gate(H Gate) to the Qubit, which changes the state of the Qubit from |0> to a state of superposition 1/sqrt(2) |0> + 1/sqrt(2) |1>. In this state of superposition, the probability of obtaining both 0 and 1 upon measurement is equal. Therefore, we measure the Qubit in this state of superposition.

# Applying Hadamard Gate on the first Qubit
qc.h(0)

# Measuring the state of the Qubit onto classical bit
qc.measure(0, 0)

Before running the Quantum Program, let’s visualize the circuit.

# Drawing the Circuit
qc.draw()

The output of this will be-

Quantum Circuit for Coin Tossing Example

Running the Quantum Program

We will now run the Quantum Program for a total of 10,000 times.

# Creating the Simulator
simulator = Aer.get_backend('aer_simulator')

# Running the Quantum Program for 10000 times
results = simulator.run(qc, shots=10000).result()

# Getting the counts of 0 and 1 in the results
counts = results.get_counts()

# printing counts
print(counts)

The output of this will be-

Results of Running the Quantum Program

Note– Even though the probability of both 0 and 1 is 0.5 each, the number of times they actually occur when running the program for 10,000 times does NOT have to 5000 each. As the number of times the program runs(shots parameter) keeps on increasing, the number of heads and tails actually occurring keep on moving close to their actual probabilities. This effect is known as the Law of Large Numbers.

Plotting Histogram

Lets plot the histogram for the results now.

# Plot Histogram
plot_histogram(counts)

The output of this will be-

Histogram for Coin Tossing Example