{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Quantum Die" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import math\n", "from pyquil import Program, get_qc\n", "from pyquil.gates import H" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "def qubits_needed(number_of_sides):\n", " \"\"\"\n", " The number of qubits needed for a die of n faces.\n", " \"\"\"\n", " return int(math.ceil(math.log(number_of_sides, 2)))\n", "\n", "\n", "def get_qvm(number_of_sides):\n", " \"\"\"\n", " Get a QVM to simulate the requested number of sides.\n", " \"\"\"\n", " return get_qc(f\"{qubits_needed(number_of_sides)}q-qvm\")\n", "\n", "\n", "def die_program(number_of_sides):\n", " \"\"\"\n", " Generate a quantum program to roll a die of n faces.\n", " \"\"\"\n", " prog = Program()\n", " n_qubits = qubits_needed(number_of_sides)\n", " ro = prog.declare(\"ro\", \"BIT\", n_qubits)\n", " # Hadamard initialize.\n", " for q in range(n_qubits):\n", " prog.inst(H(q))\n", " # Measure everything.\n", " for q in range(n_qubits):\n", " prog.measure(q, ro[q])\n", " return prog\n", "\n", "\n", "def process_results(results):\n", " \"\"\"\n", " Convert n digit binary result from the QVM to a value on a die.\n", " \"\"\"\n", " raw_results = results[0]\n", " processing_result = 0\n", " for each_qubit_measurement in raw_results:\n", " processing_result = 2 * processing_result + each_qubit_measurement\n", " # Convert from 0 indexed to 1 indexed\n", " die_value = processing_result + 1\n", " return die_value\n", "\n", "\n", "def roll_die(qvm, number_of_sides):\n", " \"\"\"\n", " Roll an n-sided quantum die.\n", " \"\"\"\n", " die_compiled = qvm.compile(die_program(number_of_sides))\n", " return process_results(qvm.run(die_compiled))" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The result is: 2\n" ] } ], "source": [ "number_of_sides = 5\n", "\n", "qvm = get_qvm(number_of_sides)\n", "die_value = roll_die(qvm, number_of_sides)\n", "while die_value > number_of_sides:\n", " die_value = roll_die(qvm, number_of_sides)\n", "print(f\"The result is: {die_value}\")" ] } ], "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.7.3" } }, "nbformat": 4, "nbformat_minor": 4 }