How to write a quantum program in 10 lines of code (for beginners)
Build an 8-sided dice that runs on a quantum computer
(Disclosure: I’m a product manager at Rigetti Quantum Computing. We’re hiring.)
When I was first introduced to quantum computing, the thought of quantum computers alone was mindblowing; it seemed more science fiction than reality.
But what if I told you that real quantum computers exist today, and you can already write programs on them over the cloud?
Specifically, we’ll build an 8-sided quantum dice that generates a random result. Here’s our program:
Some context: I’m a product manager at Rigetti, and we’re building quantum computers that anyone can access over the cloud.
Today, there’s already thousands of developers, researchers, and organizations using the Forest SDK, with over 60M+ jobs run to date.
Near-term applications are being developed to solve some of the world’s most complex problems—such as simulating molecules that lead to the discovery of new materials and pharmaceuticals, designing catalysts to help build next generation battery technologies, and solving complex optimization problems for achieving new advancements in machine learning and artificial intelligence.
In this post, I’ll introduce you to the basics of quantum computing, demonstrate why they’re useful, and show you how easy it is to start building quantum programs.
Let’s get started.
Setup & Installation
First, you’ll need to sign up for a free API key for Forest here. Once signed up, you’ll receive your API key within a few minutes via email.
While you wait, check that you have
Python v3.x installed (you can run
python --version in your terminal to check which version you have).
If you don’t already have Python, or if you have an older 2.x version, I recommend downloading and installing the Anaconda Python distribution here.
Once you have the right version of Python, you’ll need to install pyQuil:
conda install -c rigetti pyquil
Alternatively, you can also
pip install pyquil, although some users have experienced issues with this method, so we recommend using
Now that you’ve installed pyQuil, open up your code editor, or spin up a Jupyter notebook, and create a new file named
At the top of the file, we’ll import the following:
from pyquil.quil import Program
from pyquil.api import QVMConnection
from pyquil.gates import H
from functools import reduceqvm = QVMConnection()
Here’s what we’ve imported:
- Quantum programs are written in Forest using the
Programobject, which accepts the main logic of our application.
QVMConnectionenables us to connect to a quantum virtual machine (QVM), a powerful 26-qubit simulator of a quantum computer. The QVM is great for testing and development, and towards the end of this post, I’ll show you how to replace the QVM with an API connection to the actual quantum computer itself.
His the Hadamard gate. If you aren’t familiar with the Hadamard gate, don’t worry. For now, all we need to know is that it will apply a quantum state that helps us randomize the roll of the dice. I’ll return to this below in more detail.
reduceis not a part of pyQuil, but is a commonly used function in Python for performing loops and iterative computations. Specifically, this will help us format the final result of our rolled dice into an integer value between 1 and 8.
Qubits, superposition, and quantum gates
Before moving on, let’s quickly introduce some quantum computing concepts.
In classical computers (e.g. our laptops, phones, etc), all of the interactions and information that we generate eventually gets compiled down into a series of binary bits: 0's or 1’s. Bits are the fundamental building blocks of computers.
In quantum computing, we have quantum bits, or qubits. What makes qubits unique is that they are non-binary, meaning they can be in a state of 0, 1, or a special in-between state known as superposition. While in superposition, a qubit is simultaneously both 0 and 1. When we measure the qubit, it collapses out of its quantum state and returns either a 0 or 1.
Consider this analogy: a ball starts off as either red or blue (its initial state). We put that ball inside a closed box, and while inside the box, the ball uses some quantum properties to change its color to purple—an in-between combination of both red and blue (i.e. superposition). When we open this box to observe the purple ball, suddenly it changes its color again and we only see either a red or blue ball.
We use quantum gates to help change the state of our qubits, and control them while in superposition. These are quantum operations that are analogous to the classical boolean logic gates (e.g. NOT, AND, XOR, etc.), but that have extra features because they are quantum.
For example, the quantum
X gate changes a qubit’s state from 0 to 1. The Hadamard gate,
H gate, places a qubit in superposition and generates a 50/50 random chance of measuring either a 0 or 1. Using pyQuil, we can simply import these gates into our program.
Creating the 8-sided dice with quantum bits
To illustrate how this works, let’s go back to our quantum dice program.
dice = Program(H(0), H(1), H(2))
Here we are using the the
H gate, or Hadamard gate, which we imported previously. First, we pass in a single qubit :
H(0). In pyQuil, qubits are indexed starting from 0, 1, 2, etc. We repeat this for two more qubits:
Now we have three qubits—each in superposition, and each with a random probability to return either 0 or 1 when they are measured.
This gives us 8 total possible outcomes (2 * 2 * 2 = 2³), which will represent each side for our quantum dice:
- [0, 0, 0] All three qubits are in state 0
- [0, 0, 1] The first two qubits are in state 0, the third in state 1
- [0, 1, 1] The first qubit is in state 0, the second and third in state 1
- [1, 1, 1] …
- [1, 1, 0]
- [1, 0, 1]
- [1, 0, 0]
- [0, 1, 0]
You may have noticed that each additional qubit we add to our program will double the number of sides on our dice. So, a fourth qubit would create a 16-sided dice; five qubits would generate a 32-sided dice; and so on.
This helps demonstrate one of the fundamental principles that makes quantum computing so powerful: quantum computing power scales exponentially with qubits (i.e. N qubits = 2^N bits). We only needed three qubits to generate 8 potential outcomes.
Rolling the dice
Now that we have 8 equally random outcomes, we need to generate a single result, i.e. roll the dice.
Let’s name this function
# Measure the qubits to get a result, i.e. roll the dice
roll_dice = dice.measure_all()
In a quantum environment, taking a measurement causes a qubit to collapse out of superposition. So when we call the
measure.all() method, each of our qubits are collapsed into a random state of either 0 or 1. Effectively, our measurement generates a random “roll of the dice.”
To see what’s happening under the hood, you can print the
roll_dice function. You’ll see an assemby-like set of instructions is being generated:
MEASURE 0 
MEASURE 1 
MEASURE 2 
These instructions are written in a language called Quil (Quantum Instruction Language), a compilation layer that connects pyQuil programs to the quantum computing backend. You can learn more about the design and architecture of Quil here, and check out the docs for how you can customize it using the API here.
Returning back to our
roll_dice function, we execute it by running it with the QVM:
# Execute the program by running it with the QVM
result = qvm.run(roll_dice)
An example result we’d generate from running this function is
[[0,1,0]]. The inner list represents the final state of our three qubits—one of the 8 possibilities listed above (i.e. the result of our dice roll).
Finally, let’s format the result into a nice readable dice value between 1 and 8. We’ll use the
reduce function we imported earlier to help us convert our result from a list of three qubit states to a single integer (read how reduce works).
dice_value = reduce(lambda x, y: 2*x + y, result, 0) + 1
print("Your quantum dice roll returned:", dice_value)
That’s it! Run your
quantum_dice.py file to test it out.
Moving from the QVM to the QPU
To summarize, we’ve successfully simulated an 8-sided dice on a quantum computer using Rigetti’s quantum virtual machine.
Now, let’s see how we can do this on the actual quantum computer itself.
Rigetti’s quantum processing units (QPUs), or quantum chips, are fabricated at our lab in Fremont, CA, and then wired and integrated into a dilution refrigerator in Berkeley, CA, where it’s made available over the cloud.
Currently, the Agave 8-qubit chip (8Q-Agave) is live and available for you connect to using the Forest API. You can request access to the QPU here. Your access will then be scheduled for a dedicated window of time.
Once you’ve received access, you can simply replace your connection to the QVM with a connection to the QPU in a few lines of code:
Remove the prior connection to the QVM:
# Remove this
from pyquil.api import QVMConnection
...qvm = QVMConnection()
....result = qvm.run(roll_dice)
And connect to the QPU:
from pyquil.api import QPUConnection
...qpu = QPUConnection('8Q-Agave')
...result = qpu.run(roll_dice)
Next steps and helpful links
We introduced how qubits, superposition, and quantum gates work in quantum programming, and built a quantum program in just 10 lines of code. We also demonstrated the exponential scaling power of quantum computers (N qubits = 2^N bits).
As a challenge for the next step in your quantum programming journey, how would you build a quantum dice with a generalized N number of sides?
We’d love for you to try out the challenge and publish a post on how you did it. Also, join our Slack community to connect with others exploring quantum computing and Forest, as well as with our team at Rigetti.
Finally, here’s some recommended resources I’ve found helpful to getting started in quantum computing:
- Quantum Computation and Quantum Information by Michael Neilsen and Isaac Chuang. Most commonly recommended book for beginners. Tip: don’t get hung up on Chapter 1.
- Quantum Computing Explained by David McMahon. A helpful supplement to the the book above, in particular for explaining linear algebra concepts in more detail.
- Quantum Computing for the Determined: YouTube series by Michael Nielsen. Helpful complement to his book listed above.
- Essence of Linear Algebra: YouTube series that reviews linear algebra concepts with helpful visualizations.
Podcasts / Talks:
- a16z Podcast: Quantum Computing, Now and Next with Chad Rigetti and Chris Dixon
- a16z Podcast: The Cloud Atlas to Real Quantum Computing with Jeff Cordova, Vijay Pande, and Sonal Chokshi
- Y Combinator Podcast: John Preskill on Quantum Computing
- Meet the meQuanics: Weekly episodes with active researchers, leaders, and entrepreneurs in quantum computing
- Programming the world’s first quantum computers using Forest: Presentation by Will Zeng, Head of Quantum Cloud Services at Rigetti
Note: Another important benefit of quantum computing we demonstrated in this example is using quantum computers for random number generation. While this is a simple operation we already do today, the threat of being able to reverse engineer or manipulate these techniques makes many of today’s cryptographic systems vulnerable. With quantum computing, this randomization is performed and hidden by nature in the quantum world. This not only helps to generate true randomness but also protects the randomization operation from any attempts to observe or intercept it, as this would disturb and collapse the quantum environment.
Thanks to Will Zeng, Lauren Rugani, and Nima Alidoust for your feedback and edits.