·

# Quantum Random Number Generator (in progress)

### 1. Introduction

This is the experimental code for a quantum random number generator which can be run on a real quantum computer. I will provide detailed information about how the code works and many optimizations soon. The tutorial series will be found on my YouTube channel in both German and English.

### 2. Code

import math
from qiskit import *
from qiskit import IBMQ
from qiskit.tools.monitor import job_monitor

"""
Quantum Random Number Generator Class
@author: Florian André Dalwigk
@version: 1.0
"""
class QuantumRandomNumberGenerator:
def __init__(self, min, max):
# Error-Check, TODO
# How many rounds?
self.diff = max - min
# How many bits?
self.bits = math.ceil(math.log2(self.diff))
# Create dictionary
self.numbers = {}
self.set_machine("sim")
tmp = min
print("--- initialize generator ---")
for i in range(self.diff):
self.numbers["{0:b}".format(i).zfill(self.bits)] = tmp
tmp += 1
print("--- initialization completed ---")

"""
Generates a random number in between <min> and <max>.
"""
def random_number(self):
# Quantum register
qr = QuantumRegister(self.bits)

# Classical register
cr = ClassicalRegister(self.bits)

# Quantum circuit
qc = QuantumCircuit(qr, cr)

# Hadamard transformation for all Qubits.
for i in range(self.bits):
qc.h(i)
qc.measure(i,i)

key = ""

while key not in self.numbers:
# Generate key.
job = execute(qc, backend=self.machine, shots=1)
job_monitor(job)
result = job.result()
key = str(list(result.get_counts(qc).keys())[0])
return self.numbers[key]

"""
Sets the machine to either "sim" (simulator) or "IBM" (IBM Quantum Computer)
"""
def set_machine(self, machine):
if machine == "sim":
self.machine = Aer.get_backend('qasm_simulator')
print("--- machine is set to SIMULATOR ---")
elif machine == "ibm":
self.machine = IBMQ.get_provider('ibm-q').get_backend('ibmq_16_melbourne')
print("--- machine is set to IBM ---")
else:
raise RuntimeError("No valid machine chosen!")

"""
Create a random Qubit (0 or 1)
"""
def random_qubit(self):
# Quantum register
qr = QuantumRegister(1)

# Classical register
cr = ClassicalRegister(1)

# Quantum circuit
circuit = QuantumCircuit(qr, cr)

circuit.h(0)

# Measure and destroy the superposition
circuit.measure(0,0)

job = execute(circuit, backend=self.machine, shots=1)
job_monitor(job)

# Generate and return bit.
return str(list(job.result().get_counts().keys())[0])


Kommentar schreiben

Kommentare: 0