Skip to content

Instantly share code, notes, and snippets.

@splch
Last active July 15, 2021 04:01
Show Gist options
  • Save splch/87d5a5a57ec60ab87c4e190fa88c43f6 to your computer and use it in GitHub Desktop.
Save splch/87d5a5a57ec60ab87c4e190fa88c43f6 to your computer and use it in GitHub Desktop.
Basic QRNG Implementation
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"id": "88aa4ff3",
"metadata": {},
"source": [
"# Quantum Random Number Generator"
]
},
{
"cell_type": "markdown",
"id": "23645a59",
"metadata": {},
"source": [
"## Imports"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "8b59b39c",
"metadata": {},
"outputs": [],
"source": [
"from qiskit import Aer, execute, QuantumCircuit\n",
"from random import random, randint"
]
},
{
"cell_type": "markdown",
"id": "ab6012b5",
"metadata": {},
"source": [
"## Helper Functions"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "4a372a5b",
"metadata": {},
"outputs": [],
"source": [
"def execute_qc(qc):\n",
" backend_sim = Aer.get_backend('qasm_simulator')\n",
" sim = execute(qc, backend_sim, shots=1)\n",
" sim_result = sim.result()\n",
" counts = sim_result.get_counts(qc)\n",
" return int(list(counts.keys())[0].split(' ')[0], 2)\n",
"\n",
"def qrng(num_qubits):\n",
" qc = QuantumCircuit(num_qubits, num_qubits)\n",
" qc.h(range(num_qubits))\n",
" qc.measure_all()\n",
" return execute_qc(qc)\n",
"\n",
"def qrandom():\n",
" num_qubits = 10\n",
" qrn = qrng(num_qubits)\n",
" return qrn / int('1' * num_qubits, 2)\n",
"\n",
"def qrandint(a, b):\n",
" _min = 0\n",
" _max = b - a\n",
" num_qubits = len(bin(_max)[2:])\n",
" qrn = _max + 1\n",
" while qrn > _max:\n",
" qrn = qrng(num_qubits)\n",
" return a + qrn"
]
},
{
"cell_type": "markdown",
"id": "82c6557c",
"metadata": {},
"source": [
"## Random Number Generation"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "eb9171c8",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"randint(1,10)"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "af8e5c83",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"qrandint(1,10)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.8"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment