Q#
덤프버전 :
1. 개요[편집]
Q#은 2017년에 발표된 양자컴퓨터의 양자 알고리즘을 개발하고 실행하기 위한 Microsoft의 오픈 소스 프로그래밍 언어이다.
2. 역사[편집]
2017년 9월 26일 Microsoft Ignite Keynote에서 Microsoft는 양자 컴퓨터를 위해 특별히 설계된 새로운 프로그래밍 언어를 출시할 것이라고 발표했다. 2017년 12월 11일에는 Microsoft는 .NET 프로젝트의 SDK인 Quantum Development Kit(QDK)의 일부로 Q#을 출시했다. 이후 Build 2019빌드에서 Microsoft는 Q# 컴파일러와 시뮬레이터를 포함한 Quantum Development Kit를 오픈소싱한다고 발표했다.
3. 기능[편집]
Q#의 주요 기능은 양자 알고리즘용 큐비트를 만들고 사용하는 기능이다. 결과적으로 Q#의 가장 두드러진 기능 중 일부는 각각 Controlled NOT 게이트 및 Hadamard 게이트를 통해 큐비트에 중첩 및 중첩제어를 도입 하는 기능과 Tofffoli Gates , Pauli X, Y, Z 게이트 등을 포함하는 기능이다.
결국 Q#과 함께 제공될 하드웨어 스택은 큐비트를 토폴로지 큐비트로 구현할 것으로 예상된다. 현재 Quantum Development Kit와 함께 제공되는 양자 시뮬레이터는 사용자 컴퓨터에서 최대 32큐비트를 처리하고 Azure에서는 최대 40큐비트를 처리할 수 있다.
Quantum Development Kit에서 제공하는 기능들은 다음과 같다.
- Azure Quantum 서비스에 Qiskit[1] 및 Cirq 애플리케이션을 제출하는 Python 패키지
- Q# 프로그래밍 언어 및 라이브러리
- Jupyter Notebook에서 Q#을 실행하기 위한 IQ# 커널
- Azure Quantum 서비스를 관리하고 Q# 애플리케이션을 제출하는 Azure CLI 확장
- Q#을 포함하여 Python 및 .NET 언어용(C\#, F\# 및 VB.NET) API
- Visual Studio Code 및 Visual Studio용 확장
4. 특징[편집]
4.1. C\#와의 비교[편집]
- 네임스페이스를 통한 필드 분리
- 세미콜론으로 문장 마침
- 중괄호사용
- 한줄 주석은
을 통해 작성//
-
,Int
,String
등과 같은 데이터 타입은 대문자로 시작Double
-
을 사용하여 람다함수 작성=>
-
키워드로 결과 반환return
4.2. F\#와의 비교[편집]
- 변수는 let또는 mutable을 사용하여 선언
- 1차 함수
- open키워드를 사용하여 모듈 가져오기
- 데이터 유형은 변수 이름 뒤에 선언
- 범위 연산자
..
-
루프for … in
- 모든 작업/함수는 void가 아닌 빈 튜플 반환
- 레코드 데이터 유형의 정의 (
대신type
키워드 사용)newtype
5. 예제[편집]
5.1. 난수 생성기[편집]
이 예제는 Microsoft의 공식 문서 중 연습-양자 난수 생성기 만들기에서 가져왔습니다.
namespace QuantumRNG {
open Microsoft.Quantum.Canon;
open Microsoft.Quantum.Intrinsic;
open Microsoft.Quantum.Measurement;
open Microsoft.Quantum.Math;
open Microsoft.Quantum.Convert;
operation GenerateRandomBit() : Result {
// Allocate a qubit.
use q = Qubit();
// Put the qubit to superposition.
H(q);
// It now has a 50% chance of being measured 0 or 1.
// Measure the qubit value.
return M(q);
}
operation SampleRandomNumberInRange(max : Int) : Int {
mutable output = 0;
repeat {
mutable bits = [];
for idxBit in 1..BitSizeI(max) {
set bits += [GenerateRandomBit()];
}
set output = ResultArrayAsInt(bits);
} until (output <= max);
return output;
}
@EntryPoint()
operation SampleRandomNumber() : Int {
let max = 50;
Message($"Sampling a random number between 0 and {max}: ");
return SampleRandomNumberInRange(max);
}
}
5.2. 그래프 색 지정 문제[편집]
이 예제는 Microsoft의 공식 문서 중 연습 - Grover 알고리즘을 구현하여 그래프 색 지정 문제 해결에서 가져왔습니다.
namespace ExploringGroversSearchAlgorithm {
open Microsoft.Quantum.Measurement;
open Microsoft.Quantum.Math;
open Microsoft.Quantum.Arrays;
open Microsoft.Quantum.Canon;
open Microsoft.Quantum.Convert;
open Microsoft.Quantum.Diagnostics;
open Microsoft.Quantum.Intrinsic;
operation MarkColorEquality(c0 : Qubit[], c1 : Qubit[], target : Qubit) : Unit is Adj+Ctl {
within {
for (q0, q1) in Zipped(c0, c1) {
CNOT(q0, q1);
}
} apply {
(ControlledOnInt(0, X))(c1, target);
}
}
operation MarkValidVertexColoring(
edges : (Int, Int)[],
colorsRegister : Qubit[],
target : Qubit
) : Unit is Adj+Ctl {
let nEdges = Length(edges);
let colors = Chunks(2, colorsRegister);
use conflictQubits = Qubit[nEdges];
within {
for ((start, end), conflictQubit) in Zipped(edges, conflictQubits) {
MarkColorEquality(colors[start], colors[end], conflictQubit);
}
} apply {
(ControlledOnInt(0, X))(conflictQubits, target);
}
}
operation ApplyMarkingOracleAsPhaseOracle(
markingOracle : ((Qubit[], Qubit) => Unit is Adj),
register : Qubit[]
) : Unit is Adj {
use target = Qubit();
within {
X(target);
H(target);
} apply {
markingOracle(register, target);
}
}
operation RunGroversSearch(register : Qubit[], phaseOracle : ((Qubit[]) => Unit is Adj), iterations : Int) : Unit {
ApplyToEach(H, register);
for _ in 1 .. iterations {
phaseOracle(register);
within {
ApplyToEachA(H, register);
ApplyToEachA(X, register);
} apply {
Controlled Z(Most(register), Tail(register));
}
}
}
@EntryPoint()
operation SolveGraphColoringProblem() : Unit {
// Graph description: hardcoded from the example.
let nVertices = 5;
let edges = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3), (3, 4)];
// Define the oracle that implements this graph coloring.
let markingOracle = MarkValidVertexColoring(edges, _, _);
let phaseOracle = ApplyMarkingOracleAsPhaseOracle(markingOracle, _);
// Define the parameters of the search.
// Each color is described using 2 bits (or qubits).
let nQubits = 2 * nVertices;
// The search space is all bit strings of length nQubits.
let searchSpaceSize = 2 ^ (nQubits);
// The number of solutions is the number of permutations of 4 colors (over the first four vertices) = 4!
// multiplied by 3 colors that vertex 4 can take in each case.
let nSolutions = 72;
// The number of iterations can be computed using a formula.
let nIterations = Round(PI() / 4.0 * Sqrt(IntAsDouble(searchSpaceSize) / IntAsDouble(nSolutions)));
mutable answer = new Bool[nQubits];
use (register, output) = (Qubit[nQubits], Qubit());
mutable isCorrect = false;
repeat {
RunGroversSearch(register, phaseOracle, nIterations);
let res = MultiM(register);
// Check whether the result is correct.
markingOracle(register, output);
if (MResetZ(output) == One) {
set isCorrect = true;
set answer = ResultArrayAsBoolArray(res);
}
ResetAll(register);
} until (isCorrect);
// Convert the answer to readable format (actual graph coloring).
let colorBits = Chunks(2, answer);
Message("The resulting graph coloring:");
for i in 0 .. nVertices - 1 {
Message($"Vertex {i} - color {BoolArrayAsInt(colorBits[i])}");
}
}
}
6. 관련 문서[편집]
7. 외부 링크[편집]
이 문서의 내용 중 전체 또는 일부는 2023-11-02 12:56:39에 나무위키 Q# 문서에서 가져왔습니다.
[1] IBM에서 개발한 Python 기반 양자컴퓨팅 언어이다.