Building a Quantum Random Number Generator
A classical "random" number generator is actually pseudo-random: a deterministic algorithm that just looks random, given the same seed, it always produces the same sequence. A qubit in superposition is different, its measurement outcome is fundamentally, physically unpredictable, not just hard to predict. This lesson builds a genuine quantum random number generator (QRNG).
The idea
Put every qubit into an equal superposition with h, measure them all, and read the resulting bitstring as a binary number:
from qiskit import QuantumCircuit
from qiskit_aer import AerSimulator
def quantum_random_bits(n_bits):
qc = QuantumCircuit(n_bits, n_bits)
qc.h(range(n_bits)) # put every qubit into superposition
qc.measure(range(n_bits), range(n_bits))
simulator = AerSimulator()
result = simulator.run(qc, shots=1).result() # one measurement, one random bitstring
bitstring = list(result.get_counts().keys())[0]
return int(bitstring, 2) # parse the bitstring as base-2
print(quantum_random_bits(8)) # a random integer from 0 to 255
print(quantum_random_bits(8)) # a different one, genuinely unpredictable
qc.h(range(n_bits))applieshto every qubit at once,range(n_bits)expands to[0, 1, ..., n_bits - 1], and Qiskit accepts a list of qubit indices anywhere a single index is accepted.shots=1is deliberate here, unlike the last lesson, this isn't about estimating a probability distribution, it's about getting exactly one genuinely random outcome.int(bitstring, 2)parses the measured bitstring (like'10110100') as a base-2 number, converting 8 random bits into a random integer from 0-255.
Why this matters
Real quantum random number generators are used in cryptography today, precisely because their unpredictability doesn't rely on hiding an algorithm or a seed, it's a fundamental physical property. A classical pseudo-random generator, no matter how sophisticated, is deterministic under the hood, if you know the seed and the algorithm, you can predict every "random" number it will ever produce.
TIP
Try increasing n_bits and calling quantum_random_bits several times, on a real quantum computer (not just this ideal simulator), this is genuinely how some production QRNG services work.