Q# Quantum Random Number Generator

Lou Mauget .NET, Technology Snapshot Leave a Comment

Introduction

In this blog we will:

  • Give an overview of the current status of Quantum Computing today
  • Lightly discuss basic concepts surrounding quantum qubits: quantum entanglement, Superposition, and Decoherence
  • Relate superposition to the “Bloch Sphere”
  • Obtain a random value by measuring a qubit in superposition
  • Present a Q# quantum number generator (QRNG) that generates random numbers to the console:
$ dotnet run
Hello from Quantum World!
10 Q#-generated 64-bit random integers:
	C99C2BB9BB9382D7
	893C5169F421699E
	DE73C64C49BB6D25
	9C9FE2AF89019C73
	44EB610D4A705FE3
	EBF3EBF31986D34F
	695B993CF1D17DC9
	599C3042012FB82C
	B69DDDD6A4A2F17A
	2A5EDDE0A9E5BC99
$

We’ll begin by discussing the background of quantum computing, and then, we’ll dive into a small Q# random number generation demo.

Quantum Computers

Qubits and quantum gates compose a quantum computer. A qubit corresponds to a classical computer bit…somewhat. Its characteristics defy everyday macro-world experience. A quantum gate is an operator on one or more qubits. A Hadamard gate (H) places its input qubit into a superposition state that we’ll discuss later.

If we mindfully connect a sufficient number of qubits via a selection of quantum gates, we could create a quantum task that would vastly outperform certain classical computational tasks. Additionally, it’s possible that it could complete some tasks that are thought to be impossible for classical computers – for example, the unholy grail of breaking RSA encryption.

A hardware implementation of a logical qubit typically involves thousands of physical qubits founded on elemental particles. A logical qubit derives state from a statistical vote among physical qubits. To do this, current hardware needs supercooling to near-zero degrees Kelvin.

It’s clear that you won’t own a quantum smartwatch soon.

Quantum Computing Today

Where are the practical applications?

The issue lies in this phrase: “sufficient number of qubits.” Currently, qubits are profoundly expensive and error-prone due to “noise” in them. Adding more qubits quickly compounds the issue. That is one reason for the near-zero Kelvin temperatures involved. A quantum application may run many “shots” at some kinds of tasks, plucking a statistical winner.

Most real-world applications will need vastly more qubits than the approximately 50 that some current machines provide. Luckily, our little QRNG will only need one qubit.

A quantum application concept often involves specialized algorithms that would not realistically be completed on a classical computer. Applications such as factoring large numbers can involve cooperation between a classical program and a quantum program.

Where are quantum computers?

Large organizations are making breakthroughs. Cloud-based quantum computer access for small tasks is a current or near-future on-ramp to limited quantum computing access by us, the unwashed. We have run a QRNG written in IBM’s QASM on real quantum hardware accessed via the IBM Q Experience cloud.

Check out this non-exhaustive list of enterprises working in this field:

Quantum Characteristics

We mentioned non-intuitive characteristics that defy our macro-world senses. Quantum characteristics manifest in the pico-world. For a longer, more authoritative discussion, refer to this article. If you drill down, English will give way to foundational math.

For the purposes of this blog, let’s just skim a couple of concepts at the 40,000-foot level.

Entanglement

Two or more qubits can be entangled, meaning that the state of each correlates with that of the others. Those state-mirroring qubits can be situated a great distance apart. In 2017, scientists experimentally verified entanglement at a 50-mile-separation. Entanglement has applications in the field of quantum information theory.

Enough said about entanglement here; we won’t need it for our QRNG.

Superposition

Our QRNG depends upon superposition – another strange quantum characteristic. Placing a qubit into superposition causes its state to be indeterminate until we measure it, but observation destroys the measured state! Moreover, if we don’t measure it quickly enough, it suffers spontaneous decoherence, meaning it exits superposition.

See Also:  React vs. Angular: A Comparison Between Two Great Options

With superposition, a measured value will be a 3D point, shown as |Ψ> in Dirac notation on the Bloch Sphere below. This comes across as complicated, but please relax. Convention simply designates any point in the Bloch northern hemisphere as a 0, while a point in the southern hemisphere as a 1.

Quantum Superposition Bloch Sphere

Quantum Superposition Bloch Sphere

The word on the street is that a value sequence from a qubit is as random as any sequence in nature can be. Do you see where we’re headed for the QRNG demo?

Determining a qubit’s state by observation seems intuitive, but observation clears qubit state, taking it out of superposition. How rude! It’s as if obtaining a bank account’s balance removes the account. This is one of the hurdles of quantum computing.

Einstein wasn’t a fan: “Would a sidelong glance from a mouse suffice?”

Yet quantum computing works. It’s partially built upon observing an entity that is in superposition. Measurement takes it out of superposition, yielding its state.

Our Q# demo causes a single qubit to emit a random boolean. We call our q# operation 640 times, accumulating each 64-bit result into a set of 10 random integers. We return them as a result sequence to a C# controller.

Quantum Random Number Generator (QRNG)

Our QRNG consists of three parts:

  1. A quantum computer used like a coprocessor (simulated by a Microsoft library)
  2. Microsoft Q# code that orchestrates the quantum computer in a procedural manner
  3. Microsoft C# driver code that invokes and handles the Q# code

Quantum Simulator

If we can simulate a quantum computer on a classical computer, then what is the point of a quantum computer? Well, it’s that magic entanglement characteristic mixed as well as states of superposition. The ensuing global interconnection complexity increases exponentially with the number of qubits. Simulation processing delays for heavy problems increase accordingly.

Since our QRNG uses just one qubit, a simulator is up to the task … in a pseudo-random manner.

Q# Language

Programming a raw quantum computer could involve rearranging or connecting physical hardware components. That was how users programmed the first analog computers to solve problems such as artillery ballistics.

Microsoft took another approach. Instead of interactively arranging entities in an editor, they developed Q#, a .NET language, that uses a procedural approach to abstract oddities of quantum computer hardware into a more classical language environment. This seems more accessible to some of us classical folks.

Q# supports an interface that enables delegation to pluggable backend hardware or to a quantum simulator. Our Q# currently uses a quantum simulator. Sure, this implies that our results boil down to plain old pseudo-random sequences. Nonetheless, our code would actually work on real-life quantum hardware. If Microsoft enabled the unwashed to queue jobs to actual (expensive) quantum hardware, our QRNG would be up to it.

QRNG Demo

Let’s discuss our demo QRNG from bottom-up: output first, followed by relevant code, and then, we’ll bring it home by discussing installation and execution. Our QRNG demo is a .NET Core application consisting of a C# controller invoking a Q# quantum task.

Output

A dotnet run issued from the root of our QRNG project produced the following kind of console output:

Hello from Quantum World!
10 Q#-generated 64-bit random integers:
   03D2167DDA774C0E
   ACB41924DD444D2F
   DE7A33C27DE54698
   7E5F619A4BBF04A7
   1080C9C2EEEC88A4
   FAA9505AB73900FD
   57C4786AAC2E56EF
   A48190371B476BD5
   A425B8E0492E6FEC
   90A797C20D8AC9FE

Process finished with exit code 0

Values vary with each invocation. This execution ran our core Q# fragment 10 x 64 = 640
times to accumulate that output.

Heart of The Demo

Q# is a statically-typed blend of C# and F#. A type follows a declaration but can be omitted if compile-time flow type-derivation permits.

See Also:  AWS Lambda With NestJS

The Q# QRNG operation follows. It should be readable by JavaScript, C#, Golang, or Java programmers.

   operation QuantumRandomNumberGenerator() : Int {
       mutable randomNumber = 0;
      
       // Accumulate 64 random bits, right-to-left, 
// each taken per-step from a single qubit
       for (i in 1 .. 64) {
      
           using(q = Qubit())  {   // Allocate single qubit.
               H(q);               // Hadamard gate moves qubit into superposition.
               let res = M(q);     // Measure qubit: a 50% chance of seeing 0 or 1
              
               // Accumulate to sliding bit sequence
               set randomNumber = LeftShiftedI(randomNumber, 1);
               if (res == One) {
                   set randomNumber = Or(randomNumber, 1);
               }
               Reset(q);  // We must reset released qubits
           }
       }
       return randomNumber;
   }  

This operation’s code is taken from Microsoft’s Quickstart QRN. We suggest reading this page for more details about its relevance to the Bloch Sphere.

The central logic is:

  1. Obtain a single qubit via a Q# using statement
  2. Send it to a Hadamard quantum gate that inputs the qubit, returning it in the superposition state
  3. Measure the qubit, collapsing the superposition to a random concrete state

The quantum action centers on this fragment operating on qubit, q:

   H(q);            // Hadamard gate moves qubit into superposition.
   let res = M(q);  // Measure the qubit value: a 50% chance of seeing 0 or 1.         

Q# can carry out classical operations as well. Our operation accumulates a random 64-bit integer from repeatedly placing one qubit in superposition and then measuring it. Our invoking C# driver collects ten of those Q#-generated 64-bit integers, logging each to the console:

// C#: Gen random numbers
Console.WriteLine($"{ResultCount} Q#-generated 64-bit random integers:");
for (var d = 0; d < ResultCount; d++)
{
   // Call q# processing here
   var res = QuantumRandomNumberGenerator.Run(quantumSimulator).Result;
   Console.WriteLine("{0,20:X16}", res);
}

Build and Run

It may be helpful to view the project on gitHub. View it by clicking here.

Dependencies

  • A Linux, MacOS, or Windows system capable of running .NET Core
  • .NET Core 3 (ours is 3.0.101)

Installation

.NET core makes this easy on Windows, Linux, or MacOS, no IDE needed. Carry out the following steps:

  1. dotnet new -i Microsoft.Quantum.ProjectTemplates
  2. git clone https://github.com/mauget/QSharp-Random-Gen

Verify that the cloned directory tree is this:

        ── QSharp-Random-Gen
           ├── Driver.cs
           ├── Operation.qs
           ├── QSharp-Random-Gen.csproj
           ├── QSharp-Random-Gen.sln
           ├── README.md
           └── run.sh

Run

Enter the following commands:

  1. cd QSharp-Random-Gen
  2. dotnet run

Then, verify that the console displays 10 random 64-bit numbers, as shown earlier. Run again. Verify that the numeric values differ from the first run.

That’s it. Ten distinct random numbers. End of story!

Summary

In this post, we:

  • skimmed basic concepts surrounding quantum qubits
  • discussed measuring a qubit placed into quantum superposition so as to obtain its random boolean value
  • presented a Q# program that generates random numbers to the console
  • showed how to clone and run the QRNG project on Linux, Windows, or macOS

Consult the references listed below for more details regarding the subject matter. For quick extra credit, refer to the meta summary below.

(ID AML-18370, Andrews McNeal Licensing)

References

Creative Commons Bloch Sphere image attribution to Glosser.ca

What Do You Think?