{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Meyer Penny Game" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import pyquil.quil as pq\n", "from pyquil import api\n", "from pyquil.gates import I, H, X\n", "\n", "import numpy as np" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "def meyer_penny_program():\n", " \"\"\"\n", " Returns the program to simulate the Meyer-Penny Game\n", " The full description is available in ../docs/source/exercises.rst\n", "\n", " :return: pyQuil Program\n", " \"\"\"\n", " prog = pq.Program()\n", " ro = prog.declare(\"ro\", memory_size=2)\n", " picard_register = ro[1]\n", " answer_register = ro[0]\n", "\n", " then_branch = pq.Program(X(0))\n", " else_branch = pq.Program(I(0))\n", "\n", " # Prepare Qubits in Heads state or superposition, respectively\n", " prog.inst(X(0), H(1))\n", " # Q puts the coin into a superposition\n", " prog.inst(H(0))\n", " # Picard makes a decision and acts accordingly\n", " prog.measure(1, picard_register)\n", " prog.if_then(picard_register, then_branch, else_branch)\n", " # Q undoes his superposition operation\n", " prog.inst(H(0))\n", " # The outcome is recorded into the answer register\n", " prog.measure(0, answer_register)\n", "\n", " return prog" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number of games: 10\n", "Q's winning average: 1.0\n", "Picard's flip-decision average: 0.4\n" ] } ], "source": [ "n_trials = 10\n", "qvm = api.QVMConnection()\n", "outcomes = np.asarray(qvm.run(meyer_penny_program(), [0, 1], trials=n_trials))\n", "\n", "print(\"Number of games: {}\".format(n_trials))\n", "print(\"Q's winning average: {}\".format(outcomes[:, 0].mean()))\n", "print(\"Picard's flip-decision average: {}\".format(outcomes[:, 1].mean()))" ] } ], "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 }