# Q# 的量子基础知识Quantum basics with Q#

## 先决条件Pre-requisites

• 使用首选语言和开发环境安装 Quantum 开发工具包Install the Quantum Development Kit using your preferred language and development environment
• 如果已安装 QDK，请确保将其更新至最新版本If you already have the QDK installed, make sure you have updated to the latest version

## 设置Setup

1. 使用 Q# 量子编程语言实现的一个或多个量子算法。One or more quantum algorithms, implemented using the Q# quantum programming language.
2. 使用 C# 或 Python 等编程语言实现且充当主入口点并调用 Q# 运算来执行量子算法的主机程序。A host program, implemented in a programming language like Python or C# that serves as the main entry point and invokes Q# operations to execute a quantum algorithm.
1. 为应用程序选择一个位置Choose a location for your application

2. 创建名为 Bell.qs 的文件。Create a file called Bell.qs. 此文件将包含你的 Q# 代码。This file will contain your Q# code.

3. 创建名为 host.py 的文件。Create a file called host.py. 此文件将包含你的 Python 主机代码。This file will contain your Python host code.

## 编写 Q# 运算Write a Q# operation

### Q# 运算代码Q# operation code

1. 将 Bell.qs 文件的内容替换为以下代码：Replace the contents of the Bell.qs file with the following code:

namespace Quantum.Bell {
open Microsoft.Quantum.Intrinsic;
open Microsoft.Quantum.Canon;

operation Set(desired : Result, q1 : Qubit) : Unit {
if (desired != M(q1)) {
X(q1);
}
}
}


现在可以调用此操作，将量子位设置为经典状态：100% 的情况下返回 Zero，或者 100% 的情况下返回 OneThis operation may now be called to set a qubit to a classical state, either returning Zero 100% of the time or returning One 100% of the time. ZeroOne 为常量，表示对量子位进行度量时仅有的两个可能结果。Zero and One are constants that represent the only two possible results of a measurement of a qubit.

操作 Set 用于度量量子位。The operation Set measures the qubit. 如果量子位处于所需状态，Set 会将其保留，否则会执行 X 操作，将量子位状态更改为所需状态。If the qubit is in the state we want, Set leaves it alone; otherwise, by executing the X operation, we change the qubit state to the desired state.

### 关于 Q# 运算About Q# operations

Q# 操作是量子子例程。A Q# operation is a quantum subroutine. 也就是说，它是一个包含量子操作的可调用例程。That is, it is a callable routine that contains quantum operations.

• M 操作，用于度量量子位的状态The M operation, which measures the state of the qubit
• X 操作，用于翻转量子位的状态The X operation, which flips the state of a qubit

### 添加 Q# 测试代码Add Q# test code

1. Set 运算结束后，在命名空间内将以下运算添加到 Bell.qs 文件：Add the following operation to the Bell.qs file, inside the namespace, after the end of the Set operation:

operation TestBellState(count : Int, initial : Result) : (Int, Int) {

mutable numOnes = 0;
using (qubit = Qubit()) {

for (test in 1..count) {
Set(initial, qubit);
let res = M(qubit);

// Count the number of ones we saw:
if (res == One) {
set numOnes += 1;
}
}
Set(Zero, qubit);
}

// Return number of times we saw a |0> and number of times we saw a |1>
return (count-numOnes, numOnes);
}


此运算 (TestBellState) 将循环执行 count 迭代，在量子位上设置指定的 initial 值，然后对结果进行度量 (M)。This operation (TestBellState) will loop for count iterations, set a specified initial value on a qubit and then measure (M) the result. 它将收集我们所度量的 0 和 1 的个数统计信息，并将其返回给调用方。It will gather statistics on how many zeros and ones we've measured and return them to the caller. 它执行另一个必需的运算。It performs one other necessary operation. 它将量子位重置为已知状态 (Zero)，然后将其返回，使其他人可以在已知状态下分配此量子位。It resets the qubit to a known state (Zero) before returning it allowing others to allocate this qubit in a known state. 这是 using 语句所必需的。This is required by the using statement.

### 关于 Q# 中的 using 语句About using statements in Q#

Q# 中的 using 语句也很特殊。The using statement is also special to Q#. 它用于分配要在代码块中使用的量子位。It is used to allocate qubits for use in a block of code. 在 Q# 中，所有量子位都是动态分配和释放的，而不是在复杂算法的整个生命周期内都存在的固定资源。In Q#, all qubits are dynamically allocated and released, rather than being fixed resources that are there for the entire lifetime of a complex algorithm. using 语句在代码块的开头分配一组量子位，并在代码块的末尾释放这些量子位。A using statement allocates a set of qubits at the start, and releases those qubits at the end of the block.

## 创建主机应用程序代码Create the host application code

1. 打开 host.py 文件，并添加以下代码：Open the host.py file and add the following code:

import qsharp

from qsharp import Result
from Quantum.Bell import TestBellState

initials = (Result.Zero, Result.One)

for i in initials:
res = TestBellState.simulate(count=1000, initial=i)
(num_zeros, num_ones) = res
print(f'Init:{i: <4} 0s={num_zeros: <4} 1s={num_ones: <4}')


### 关于主机应用程序代码About the host application code

Python 主机应用程序包含三个部分：The Python host application has three parts:

• 计算量子算法所需的任何参数。Compute any arguments required for the quantum algorithm. 在示例中，count 固定为 1000，initial 是量子位的初始值。In the example, count is fixed at a 1000 and initial is the initial value of the qubit.
• 通过调用所导入 Q# 运算的 simulate() 方法来运行量子算法。Run the quantum algorithm by calling the simulate() method of the imported Q# operation.
• 处理运算结果。Process the result of the operation. 在示例中，res 接收运算的结果。In the example, res receives the result of the operation. 此结果是模拟器所度量 0 的个数 (num_zeros) 和 1 的个数 (num_ones) 的元组。Here the result is a tuple of the number of zeros (num_zeros) and number of ones (num_ones) measured by the simulator. 我们通过析构元组来获取两个字段，然后打印结果。We deconstruct the tuple to get the two fields, and print the results.

## 生成并运行Build and run

1. 在终端运行以下命令：Run the following command at your terminal:

python host.py


此命令将运行模拟 Q# 运算的主机应用程序。This command runs the host application, which simulates the Q# operation.

Init:0    0s=1000 1s=0
Init:1    0s=0    1s=1000


## 准备叠加Prepare superposition

X(qubit);
let res = M(qubit);


Init:Zero 0s=0    1s=1000
Init:One  0s=1000 1s=0


H(qubit);
let res = M(qubit);


Init:Zero 0s=484  1s=516
Init:One  0s=522  1s=478


## 准备展示纠缠Prepare entanglement

using ((q0, q1) = (Qubit(), Qubit())) {


Set(initial, q0);
Set(Zero, q1);

H(q0);
CNOT(q0, q1);
let res = M(q0);


Set(Zero, q0);
Set(Zero, q1);


    operation TestBellState(count : Int, initial : Result) : (Int, Int) {

mutable numOnes = 0;
using ((q0, q1) = (Qubit(), Qubit())) {
for (test in 1..count) {
Set (initial, q0);
Set (Zero, q1);

H(q0);
CNOT(q0,q1);
let res = M(q0);

// Count the number of ones we saw:
if (res == One) {
set numOnes += 1;
}
}

Set(Zero, q0);
Set(Zero, q1);
}

// Return number of times we saw a |0> and number of times we saw a |1>
return (count-numOnes, numOnes);
}


    operation TestBellState(count : Int, initial : Result) : (Int, Int, Int) {
mutable numOnes = 0;
mutable agree = 0;
using ((q0, q1) = (Qubit(), Qubit())) {
for (test in 1..count) {
Set(initial, q0);
Set(Zero, q1);

H(q0);
CNOT(q0, q1);
let res = M(q0);

if (M(q1) == res) {
set agree += 1;
}

// Count the number of ones we saw:
if (res == One) {
set numOnes += 1;
}
}

Set(Zero, q0);
Set(Zero, q1);
}

// Return number of times we saw a |0> and number of times we saw a |1>
return (count-numOnes, numOnes, agree);
}


import qsharp

from qsharp import Result
from Quantum.Bell import TestBellState

initials = {Result.Zero, Result.One}

for i in initials:
res = TestBellState.simulate(count=1000, initial=i)
(num_zeros, num_ones, agree) = res
print(f'Init:{i: <4} 0s={num_zeros: <4} 1s={num_ones: <4} agree={agree: <4}')


Init:Zero 0s=499  1s=501  agree=1000
Init:One  0s=490  1s=510  agree=1000


## 下一步是什么？What's next?

Grover 搜索快速入门介绍了如何生成并运行 Grover 搜索（最常用的量子计算算法之一），并通过一个很好的 Q# 程序示例演示了如何使用量子计算来解决实际问题。The QuickStart Grover’s search shows you how to build and run Grover search, one of the most popular quantum computing algorithms and offers a nice example of a Q# program that can be used to solve real problems with quantum computing.