Snake_Byte[4]: Random and PseudoRandom Numbers

Expose yourself to as much randomness as possible.

~ Ben Casnocha
Visualization of the algorithmic random data
A Visualization Of Randomness

First i trust everyone is safe.

Second it is WEDNESDAY and that must mean a Snake_Byte or you are working in a startup because every day is WEDNESDAY in a startup!

i almost didn’t get this one done because well life happens but i want to remain true to the goals herewith to the best of my ability.

So in today’s Snake_Byte we are going to cover Random and PseudoRandom Numbers.  i really liked this one because it was more in line with scientific computing and numerical optimization.

The random module in Python generates what is called pseudorandom numbers.  It is in the vernacular a pseudorandom number generator (PRNG).  This generation includes different types of distributions for said numbers. 

So what is a pseudorandom number:

“A pseudorandom number generator (PRNG), also known as a deterministic random bit generator, is an algorithm for generating a sequence of numbers whose properties approximate the properties of sequences of random numbers.” ~ Wikipedia

The important aspect here is:  the properties approximate sequences of random numbers.  So this means that it is statistically random even though it was generated by a deterministic response.

While i have used the random module and have even generated various random number algorithms i learned something new in this blog.  The pseudorandom number generator in Python uses an algorithm called the Mersenne Twister algorithm.  The period of said algorithm is length 2**19937-1 for the 32 bit version and there is also a 64-bit version.  The underlying implementation in C is both fast and thread-safe. The Mersenne Twister is one of the most extensively tested random number generators in existence. One issue though is that due to the deterministic nature of the algorithm it is not suitable for cryptographic methods.

Let us delve down into some code into the various random module offerings, shall we?

i like using %system in Jupyter Lab to create an interactive session. First we import random. Lets look at random.random() which returns a uniform distribution and when multiplied by a integer bounds it within that distribution range:

import random
for i in range (5):
    x = random.random() * 100
    print (x)

Next let us check out random.choice(seq) which returns a random element from the non-empty sequence seq. If seq is empty, raises IndexError:

for z in range (5):
mySurfBoardlist = ["longboard", "shortboard", "boogieboard"]

Next let us look at random.randrange(startstop[, step]) which returns a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)) but doesn’t actually build a range object.

startOptional. An integer specifying at which position to start.
Default 0
stopRequired. An integer specifying at which position to end.
stepOptional. An integer specifying the incrementation.
Default 1
random.ranrange parameters
for i in range (5): 
      print(random.randrange(10, 100,1))

Now let us move on to some calls that you would use in signal processing, statistics or machine learning. The first one is gauss(). gauss() returns a gaussian distribution using the following mathematics:

\Large f(x) = \frac{1}{\sigma\sqrt{2\pi}}\exp\left(-\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^{2}\right)

Gaussian distribution (also known as normal distribution) is a bell-shaped curve (aka the bell curve), and it is assumed that during any measurement values will follow a normal distribution with an equal number of measurements above and below the mean value.

muthe mean
sigmathe standard deviation
returns a random gaussian distribution floating number
gauss() parameters
# import the required libraries 
import random 
import matplotlib.pyplot as plt 
#set the inline magic
%matplotlib inline   
# store the random numbers in a list 
nums = [] 
mu = 100
sigma = 50
for i in range(100000): 
    temp = random.gauss(mu, sigma) 
# plot the distribution 
plt.hist(nums, bins = 500, ec="red")
Gaussian Distribution in Red

There are several more parameters in the random module, setter functions, seed functions and very complex statistical functions. Hit stack overflow and give it a try! Also it doesn’t hurt if you dust off that probability and statistics textbook!

As a last thought which came first the framework of entropy or the framework of randomness? As well as is everything truly random? i would love to hear your thought in the comments!

Until then,

#iwishyouwater <- click here on this one!



Python In A Nutshell by Alex Martelli

M. Matsumoto and T. Nishimura, “Mersenne Twister: A 623-dimensionally equidistributed uniform pseudorandom number generator”, ACM Transactions on Modeling and Computer Simulation Vol. 8, No. 1, January pp.3–30 1998

Muzak To Muzak To Blog By:  Black Sabbath  – The End: Live In Birmingham

Hello Multi-Worlds With IBM Q

“If you are not completely confused by quantum mechanics, you do not understand it.”
~ John Wheeler

A chandelier or computing device?


i wanted to take advantage of the #socialdistancing to catch up on personal blog writing. One of the areas that i have been meaning to start is my sojourn into the area of Quantum Computing specifically with IBM Q framework Qiskit (pronounced KIZ-KIT). Qiskit is an open-source quantum computing software development framework for leveraging today’s quantum processors in research, education, and business. Having read many of the latest texts (which i will add at the end of the blog) as well as initially implementing some initial Hello_World python scripts i decided to put it away due to the fact it made Alice In Wonderland’s Rabbit hole look tame. I did, however, go through some of the initial IBM Learnings and received the following:

I am Bonafide

So given that i decided to fully re-engage and start the process the first steps as with any language or framework is to create the proverbial “Hello_World”. However, before we get into the code lets address what is in the Qiskit coding framework.

The following components are within the Qiskit framework: Terra, Aer, Aqua, and Ignis:

  • Terra: Within Terra is a set of tools for composing quantum programs at the level of circuits and pulses, optimizing them for the constraints of a particular physical quantum processor, and managing the batched execution of experiments on remote-access backends.
    • User Inputs (Circuits, and Schedules), Quantum Circuit, Pulse Schedule
    • Transpilers and optimization passes
    • Providers: Aer, IBM Quantum, and Third Party
    • Visualization and Quantum Information Tools (Histogram, State, Unitary, Entanglement)
  • Aer : It contains optimized C++ simulator backends for executing circuits compiled in Qiskit Terra and tools for constructing highly configurable noise models for performing realistic noisy simulations of the errors that occur during execution on real devices.
    • Noise Simulation (QasmSimulator Only)
    • Backends ( QasmSimulator, StatevectorSimulator, UnitarySimulator)
    • Jobs and Results: Counts, Memory, Statevector, Unitary, Snapshots
  • Aqua: Libraries of cross-domain quantum algorithms upon which applications for near-term quantum computing can be built. Aqua is designed to be extensible and employs a pluggable framework where quantum algorithms can easily be added.
    • Qiskit Aqua Translators ( Chemistry, AI, Optimization, Finance )
    • Quantum Algorithms ( QPE, Grover, HHL, QSVM, VQE, QAOA, etc… )
    • Qiskit Terra ( Compile Circuits)
    • Providers: Aer, IBM Quantium and Third Party
  • Ignis: A framework for understanding and mitigating noise in quantum circuits and systems. The experiments provided in Ignis are grouped into the topics of characterization, verification and mitigation.
    • Experiments: List of Quantum Circuits and Pulse Schedules
    • Qiskit Terra: Compile Circuits or Schedules
    • Providers: Qiskit Aer, IBM Quantum, Third Party
    • Fitters / Filters: Fit to a Model/Plot Results, Filter Noise

As one can see the components are cross-referenced across the entirety of the framework and provide the quantum developer a rich set of tools, algorithms, and methods for code creation.

Putting Your Toe In The First Quantum World

This section covers very basic quantum theory. There are several great textbooks on this subject and i will list some at the end of the blog with brief reviews. Suffice to say you cannot be scared or shy away from “greek letters or strange symbols”. To fully appreciate what is happening you need “the maths”. That said let us first define a qubit. Classical Computers operate on ( 0 ) or ( 1 ). Complete binary operations due to the nature of a diode or gate. Quantum Computers operate on quBits for Quantum Bits. These are represented by surrounding a name by ” | ” and ” > “. Thus a Qubit “named” “1” can be written as | 1\rangle. This notation is known as Dirac’s bra-ket notation. Specifically from a mathematical standpoint and this is why the above uses the label “named” it is represented by a two-dimensional vector space over complex numbers \mathbb{C}^2. This means that a Qubit takes two complex numbers to fully describe it. Okay so think about that… It takes two numbers to describe the state. Already strange huh? The computational (or standard) basis corresponds to the two levels |0\rangle and |1\rangle, which corresponds to the following vectors:

    \[\begin{split}|0\rangle = \begin{pmatrix}1\\ 0 \end{pmatrix}~~~~|1\rangle=\begin{pmatrix}0\\1\end{pmatrix}\end{split}\]

So remember that the state is described by two complex numbers. Well, the qubit does not always have to be in either |0\rangle or |1\rangle ; it can be in an arbitrary quantum state, denoted |\psi\rangle, which can be any superposition (|\psi\rangle\ = \alpha|0\rangle + \beta|1\rangle of the basis vectors. The superposition quantities \alpha and (\beta\) are complex numbers; together they obey |\alpha|^2 + |\beta| = 1 . Interesting things happen when quantum systems are measured, or observed. Quantum measurement is described by the Born rule. In particular, if a qubit in some state |\psi\rangle, is measured in the standard basis, the result 0 is obtained with probability |\alpha|^2, and the result 1 is obtained with the complementary probability |\beta|^2. Interestingly, a quantum measurement takes any superposition state of the qubit, and projects it to either the state |0\rangle or the state |1\rangle, with a probability determined from the parameters of the superposition. Whew! What i found really cool was that all of the linear algebra is the same. Here is another really cool thing: To actually create the environment the amazing scientists at IBM In the IBM Quantum Lab keep the temperature cold (15 milliKelvin in a dilution refrigerator) that there is no ambient noise or heat to excite the superconducting qubit. It is beyond the scope of why this is needed but suffices to say it involves making a superconductor, and that is when a material conducts electricity without encountering any resistance, thus without losing any energy. Ok, let’s climb out of Alice’s Rabbit Hole and get to some practical code.

Setting Up The Environment

So we are assuming the reader is familiar with setting up a python virtual environment and able to either pip install or utilize a package manager like anaconda for installing the respective libraries. The complete installation process can be found here: Installing QisKit. For completeness, i will duplicate the cogent items in the following sections. i’ll also be posting a Juypyter Notebook to github.

The simplest way to use environments is by using the conda command, included with Anaconda. A Conda environment allows you to specify a specific version of Python and set of libraries. Open a terminal window in the directory where you want to work.

Create a minimal environment with only Python installed in it.

conda create -n name_of_my_env python=3 
source activate name_of_your_env

Next, install the Qiskit package, which includes Terra, Aer, Ignis, and Aqua. ( in this writeup i will only focus on the very basics. i will get to the others in later posts! )

pip install qiskit

NOTE: Starting with Qiskit 0.13.0 pip 19 or newer is needed to install qiskit-aer from precompiled binary on Linux. If you do not have pip 19 installed you can run pip install -U pip to upgrade it. Without pip 19 or newer this command will attempt to install qiskit-aer from sdist (source distribution) which will try to compile aer locally under the covers.

If the packages installed correctly, you can run conda list to see the active packages in your virtual environment.

There are some optional packages i suggest installing for really cool circuits visualizations and like that work in conjunction with matplotlib. You can install these optional dependencies by with the following command:

pip install qiskit-terra[visualization]

To check if everything is running hop into the python prompt and type:

import Qiskit

Getting an IBM Q account and API Key

Next, you will need to register for an IBM Q account. Click this link -> Register For IBM Q Account

Here is link just in case:

IBM Q allows you to interface directly with IBM’s remote quantum hardware and quantum simulation devices. You can execute code locally on a quantum simulator however getting access to the hardware and understanding how noise affects the circuits and measurements are crucial in understanding quantum algorithm development. As with any remote system you need to lock it to an API Key. When you login you will see the following:

Generate the API token and then click on Copy API Token to copy your API Token and place into into your Jupyter Notebook. I recommend using JupyterLab Credential Store for these types of tokens and login credentials. We will come back to using the API Key so dont misplace it!

So i am assuming you made it this far and have your venv activated and your Jupyter Lab / Notebook up and running.

Check your installation by performing the following. It should print out the latest version. Also run the following commands to store your API token locally for later use in a configuration file called qiskitrc. Replace MY_API_TOKEN with the API token value that you stored in your text editor or Jupyter Notebook. Note this method saves the credentials and token to disc. It is a matter of taste you can choose in session usage as well. These are some standard imports.

%matplotlib inline
import numpy as np
from qiskit import * 
from qiskit import IBMQ
from import plot_histogram


[1]: 0.12.0

i appear to be up to date.

Next you want to make sure you are up to date on the latest versioning of the platform. Since November 2019 (and with version 0.4 of this qiskit-ibmq-provider package), the IBM Quantum Provider only supports the new IBM Quantum Experience, dropping support for the legacy Quantum Experience and Qconsole accounts. The new IBM Quantum Experience is also referred to as v2, whereas the legacy one and Qconsole as v1.


Depending on your credentials you will either get a listing of updating credentials or that you are up to date.

IBM Q has various backends to run your code upon. The default is a full-fledged simulator that is invoked locally which is very convenient. The next invocation method is via direct quantum computing hardware access. i must say it is astounding that one can access via open-source quantum computing resources.

By default, all IBM Quantum Experience accounts have access to the same, open project (hub: ibm-q, group: open, project: main). For convenience, the IBMQ.load_account() and IBMQ.enable_account() methods will return a provider for that project. If you have access to other projects, you can use:

provider_2 = IBMQ.get_provider(hub='MY_HUB', group='MY_GROUP', project='MY_PROJECT')

i used the following to check out the available backends that are available. Note: The name is just a name – not the location of the hardware:

provider = IBMQ.get_provider(group='open')
[10:] [<IBMQSimulator('ibmq_qasm_simulator') from IBMQ(hub='ibm-q', group='open', project='main')>,
 <IBMQBackend('ibmqx2') from IBMQ(hub='ibm-q', group='open', project='main')>,
 <IBMQBackend('ibmq_16_melbourne') from IBMQ(hub='ibm-q', group='open', project='main')>,
 <IBMQBackend('ibmq_vigo') from IBMQ(hub='ibm-q', group='open', project='main')>,
 <IBMQBackend('ibmq_ourense') from IBMQ(hub='ibm-q', group='open', project='main')>,
 <IBMQBackend('ibmq_london') from IBMQ(hub='ibm-q', group='open', project='main')>,
 <IBMQBackend('ibmq_burlington') from IBMQ(hub='ibm-q', group='open', project='main')>,
 <IBMQBackend('ibmq_essex') from IBMQ(hub='ibm-q', group='open', project='main')>,
 <IBMQBackend('ibmq_armonk') from IBMQ(hub='ibm-q', group='open', project='main')>]

Running Your First Circuits

There are several ways to run your first circuits. There is online access via in place Jupyter Notebooks as well as a visual circuit designer called IBM Circuit Composer which you can access via your IBM Q account. i will be describing steps using python code and direct Qiskit usage due to flexibility, transparency, and granularity over the environment. This will set it to the 'ibmq_qasm_simulator'

my_provider = IBMQ.get_provider()

So some terminology registers are used to create circuits. Circuits act upon registers. Now lets actually look at some code that generates some registers as well as a quantum circuit:

Here we a script that starts off with an input of 2 quantum “0” bits There is no action before it outputs a classical equivalent of bits:

So if you run this you will get the output:

Total count for 00 and 11 are: {'00': 517, '11': 483}

Here is what is happening:

  • QuantumCircuit.h(0): A Hadamard gate 𝐻on qubit 0, which puts it into a superposition state.
  •, 1): A controlled-Not operation (𝐶𝑋) on control qubit 0 and target qubit 1, putting the qubits in an entangled state.
  • QuantumCircuit.measure([0,1], [0,1]): if you pass the entire quantum and classical registers to measure, the ith qubit’s measurement result will be stored in the ith classical bit.
Your First Quantum Circuit

So this is an ASCII printout. i was really impressed when i found out this tidbit. You can also pass in “mpl” for matplotlib or “latex” for full on latex beautification!

circuit.draw("mpl") and circuit.draw("latex")
Matplotlib representation of the circuit

NOTE: The latex and latex_source drawers need pylatexenc installed. Run "pip install pylatexenc" before using the latex or latex_source drawers. Professor Donald Knuth will be pleased.

#Plot a histogram
Histogram showing the probability of results

The observed probabilities 𝑃𝑟(00) and 𝑃𝑟(11) are computed by taking the respective counts and dividing by the total number of shots.

Next Steps

So this is just a small step into the world of quantum programming. Below i have included several resources for study. If you are interested in pursuing this area i do urge you to take your time. i hope this at least gives you a perspective and provides a vehicle for entry. i personally feel completely humbled every time i start to read or re-read something in this area. Quantum computing is going to change the way view our world. i for one will be going deeper in this area as far as i am intellectually capable of taking the process.

NOTE: This the title of this blog refers to the theory of Minowski Multi-Worlds with a pun on Hello_World. The many-worlds interpretation implies that there is a very large—perhaps infinite number of universes. It is one of many multiverse hypotheses in physics and philosophy. MWI views time as a many-branched tree, wherein every possible quantum outcome is realized.


IBM Q User Guides All of the official IBM Q User Guides – very comprehensive.

IBM Q Wikipedia – A good readers digest of the history of IBM Q

The IBM Quantum Experience – the entry and dashboard experience

IBM Q online book – an amazing interactive experience covers everything from physics, linear algebra to code.

Mastering Quantum Computing with IBMQX – a great practical well-written book on how to get your hands coding on IBM Q

Dancing with Qubits – Written by Dr Bob Sutor of IBM a wonderful text on the mathematics and processes of quantum computing

Practical Quantum for Developers – a multi-disciplinary book that covers all aspects of coding for quantum from python, apis, cryptography, and even game theory.

Quantum Computing – A Gentle Introduction – this book covers the fundamentals of quantum computing in a very pragmatic fashion and focuses on the mathematical aspects.

Quantum Algorithms via Linear Algebra – the title is the content. ready set Linear Algebra – its the same stuff only quantum!

Quantum Computing for Computer Scientists – very close to the Gentle Introduction text however it covers the theory in-depth and also goes over several different types of algorithms.

Minowski Multi Worlds – The many-worlds interpretation implies that there is a very large perhaps infinite number of universes. It is one of many multiverse hypotheses in physics and philosophy. MWI views time as a many-branched tree, wherein every possible quantum outcome is realized. This is intended to resolve some paradoxes of quantum theory, such as the EPR paradox and Schrödinger’s cat since every possible outcome of a quantum event exists in its own universe. If you ask i’ll say the cat is dead.

Until then,