まず、新規プロジェクトを作る。Visual Studio Codeを使ってるので、下記参照。
Create a C# project, using VS Code抜粋
- Go to View -> Command Palette
- Select Q#: Create New Project
- Select Standalone console application
- Navigate to the location on the file system where you would like to create the application
- Click on the Open new project... button, once the project has been created
一番初歩っぽい、乱数発生機を使う練習
Program.qs (MSのサイトだとOperation.qsになってるけど、VS code 1.4.2 2020/1月最新版だとProgram.qsで動く)
namespace Qrng {
open Microsoft.Quantum.Intrinsic;
operation SampleQuantumRandomNumberGenerator() : Result {
using (q = Qubit()) { // Allocate a qubit.
H(q); // Put the qubit to superposition. It now has a 50% chance of being 0 or 1.
let r = M(q); // Measure the qubit value.
Reset(q);
return r;
}
}
}
に書き換えて、
Driver.csを
using System;に書き換えて terminal から"dotnet run"すると、乱数が出力された
using Microsoft.Quantum.Simulation.Core;
using Microsoft.Quantum.Simulation.Simulators;
using System.Linq;
namespace Qrng
{
class Driver
{
static void Main(string[] args)
{
using (var sim = new QuantumSimulator())
{
// First we initialize all the variables:
var bitString = "0"; // To save the bit string
int max = 50; // The maximum of the range
int size = Convert.ToInt32(Math.Floor(Math.Log(max, 2.0) + 1));
// To calculate the amount of needed bits
int output = max + 1; // Int to store the output
while (output > max) // Loop to generate the number
{
bitString = "0"; // Restart the bit string if fails
bitString = String.Join("", Enumerable.Range(0, size).Select(idx =>
SampleQuantumRandomNumberGenerator.Run(sim).Result == Result.One ? "1" : "0"
)
);
// Generate and concatenate the bits using using the Q# operation
output = Convert.ToInt32(bitString, 2);
// Convert the bit string to an integer
}
// Print the result
Console.WriteLine($"The random number generated is {output}.");
}
}
}
}
0 件のコメント:
コメントを投稿