Skip to content

Instantly share code, notes, and snippets.

@wsgac
Created February 8, 2019 16:39
Show Gist options
  • Save wsgac/e2cd21a111160e59248024e4e0c4e4a4 to your computer and use it in GitHub Desktop.
Save wsgac/e2cd21a111160e59248024e4e0c4e4a4 to your computer and use it in GitHub Desktop.
Implementation of a Bell pair creation operator in Q# together with the corresponding C# driver
namespace Bell
{
open Microsoft.Quantum.Canon;
open Microsoft.Quantum.Primitive;
// Qubit setter
operation Set (desired: Result, q1: Qubit) : Unit {
let current = M(q1);
if (desired != current) {
X(q1);
}
}
operation BellPair (count: Int) : (Int,Int,Int,Int) {
// Classical counters for storing state incidence
mutable c00 = 0;
mutable c01 = 0;
mutable c10 = 0;
mutable c11 = 0;
// Acquire a two-qubit register
using (qreg = Qubit[2]) {
// Repeat experiment 'count' times
for (i in 1..count) {
// Initialize register with zeros
Set(Zero, qreg[0]);
Set(Zero, qreg[1]);
// Apply Hadamard gate to q0
H(qreg[0]);
// Apply CNOT to q0 and q1
CNOT(qreg[0], qreg[1]);
// Perform measurement
let res0 = M(qreg[0]);
let res1 = M(qreg[1]);
// Increment incidence counters accordingly
if (res0 == Zero && res1 == Zero) {
set c00 = c00 + 1;
}
elif (res0 == Zero && res1 == One) {
set c01 = c01 + 1;
}
elif (res0 == One && res1 == Zero) {
set c10 = c10 + 1;
}
else { // (res0 == One && res1 == One)
set c11 = c11 + 1;
}
}
// Cleanup expected by the using(...) construct
Set(Zero, qreg[0]);
Set(Zero, qreg[1]);
}
// Result tuple
return (c00,c01,c10,c11);
}
}
using System;
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
namespace Bell
{
class Driver
{
static void Main(string[] args)
{
using (var qsim = new QuantumSimulator())
{
// Run the Bell pair creation operator 1000 times
var result = BellPair.Run(qsim, 1000).Result;
// Destructure the resulting tuple
var (c00, c01, c10, c11) = result;
// Print the incidence of particular two-qubit states
System.Console.WriteLine(
$"|00>: {c00} |01>: {c01} |10>: {c10} |11>: {c11}"
);
}
}
}
}
@wsgac
Copy link
Author

wsgac commented Feb 9, 2019

These two files comprise a tiny quantum program, heavily based on the Q# Tutorial. The premise here is to implement the following quantum circuit:

      +---+     +------+
q0----| H |-----|      |----
      +---+     | CNOT |
q1--------------|      |----
                +------+

The circuit transforms the initial state |00> into an entangled state 1/sqrt(2) * (|00> + |11>), called a Bell pair.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment