← Quantum Store · Guides · Lessons · Glossary · Packages · About · Türkçe
Quantum Store editors
Quantum random number generator
Download ZIP (free)The simplest useful quantum program, which makes random bytes and dice rolls by measuring qubits in superposition and checks the distribution with a chi-squared test. A Qiskit example with a guide for beginners.
Why quantum randomness?
A computer's "random" numbers really come from a formula. If the starting value is known, the same numbers can be produced again. The result of a quantum measurement, on the other hand, cannot be known in advance by the laws of nature. That is why quantum random number generators (QRNGs) are among the first quantum products sold commercially today.
The example in this package
rastgele_sayi.py:
- Applies an H gate to 8 qubits. Each qubit is in an equal superposition of 0 and 1.
- A measurement gives a number from 0 to 255 (one byte). The program makes 4000 bytes.
- Checks with a chi-squared test that the numbers are spread evenly over 16 ranges. On our test machine the value was 10.2; the limit is 30.6.
- Rolls a die with 3 qubits. It throws away the results 6 and 7 out of 0–7 and tries again, so that every face stays equally likely (rejection sampling).
Important note
Because this example runs on a simulator, the results actually come from a classical pseudo-random generator. For real quantum randomness, run the same circuit on a real quantum processor in the cloud, such as IBM's or Amazon Braket. The logic of the code does not change at all.
Next steps
- Work out how many qubits you need to make random numbers from 1 to 100 (hint: 7).
- Apply
ry(1.0)instead of H to one qubit; 0 and 1 are no longer equally likely. See the chi-squared test catch it.
Installation and running
pip install qiskit
python rastgele_sayi.py
Tested with: qiskit 2.5.2, Python 3.12.
Links
Package contents
rastgele_sayi.pyREADME.en.md— this fileREADME.md— the same guide in TurkishLICENSE— the licence of the files in this packageKAYNAK.json— a machine-readable summary of the official source
Licence
This package was prepared by the Quantum Store editors and is distributed under the MIT licence.
Quantum Store — https://hakanerdogan.com/en
Example code
The example shipped in the package, run and checked. Comments and printed messages are in Turkish; the code is the same in any language. Everything is in the ZIP.
rastgele_sayi.py
"""Kuantum rastgele sayı üreteci: süperpozisyondaki kübitleri ölçerek bayt ve zar üret (Qiskit).
Çalıştırma:
pip install qiskit
python rastgele_sayi.py
Not: Simülatör sonuçları klasik bir sözde rastgele üreteçten gelir. Gerçek kuantum
rastgeleliği için aynı devreyi gerçek bir kuantum bilgisayarda çalıştırmak gerekir.
"""
from collections import Counter
from qiskit import QuantumCircuit
from qiskit.primitives import StatevectorSampler
sampler = StatevectorSampler(seed=2026)
def rastgele_bitler(n_kubit: int, adet: int) -> list[int]:
qc = QuantumCircuit(n_kubit)
qc.h(range(n_kubit)) # Her kübit 0 ve 1'in eşit süperpozisyonunda
qc.measure_all()
veri = sampler.run([qc], shots=adet).result()[0].data.meas
return [int(b, 2) for b in veri.get_bitstrings()]
baytlar = rastgele_bitler(8, 4000)
ortalama = sum(baytlar) / len(baytlar)
print("İlk 16 bayt:", " ".join(f"{b:02x}" for b in baytlar[:16]))
print(f"Ortalama: {ortalama:.1f} (beklenen 127.5)")
# Ki-kare testi: 16 eşit aralığa düşen sayıların dağılımı düzgün mü?
kutular = Counter(b // 16 for b in baytlar)
beklenen = len(baytlar) / 16
ki_kare = sum((kutular[i] - beklenen) ** 2 / beklenen for i in range(16))
print(f"Ki-kare (15 serbestlik derecesi): {ki_kare:.1f} (%99 güvenle 30.6'dan küçük olmalı)")
def zar_at(adet: int) -> list[int]:
# 3 kübit 0-7 verir; 6 ve 7 gelirse atıp yeniden dene (reddetme örneklemesi).
sonuc: list[int] = []
while len(sonuc) < adet:
sonuc += [x + 1 for x in rastgele_bitler(3, adet) if x < 6]
return sonuc[:adet]
zarlar = zar_at(600)
dagilim = Counter(zarlar)
print("600 zar atışı:", {yuz: dagilim[yuz] for yuz in range(1, 7)})
assert 122 < ortalama < 133, ortalama
assert ki_kare < 30.6, ki_kare
assert all(70 < dagilim[yuz] < 130 for yuz in range(1, 7)), dagilim
print("Tamam: sayılar düzgün dağılıyor.")
Related concepts
- Quantum measurement · Quantum measurement ends a qubit’s superposition and returns 0 or 1, with the result chosen at random according to the amplitudes.