这是一些经典的代码,可以翻转硬币并计算你得到多少头:
def coin_count():
bit = False
counter = 0
for _ in range(500):
bit ^= random() < 0.5 # False → 50% False, 50% True
# True → 50% False, 50% True
if bit:
counter += 1
return counter
如果您多次运行此代码并制作直方图,则结果将近似为二项分布:
![经典二项分布](https://i.stack.imgur.com/y5Jcy.png)
现在这里有一些伪代码基本上做同样的事情,除了硬币被替换为 qubit。我们通过对它应用 Hadamard 操作来“翻转量子比特”。
def hadamard_coin_count():
qubit = qalloc()
counter = 0
for _ in range(500):
apply Hadamard to qubit # |0⟩ → √½|0⟩ + √½|1⟩
# |1⟩ → √½|0⟩ - √½|1⟩
if qubit: # (not a measurement; controls nested operations)
counter += 1 # (happens only in some parts of the superposition)
return measure(counter) # (note: counter was in superposition)
这样做很多次,绘制分布图,你会得到一些非常不同的东西:
![量子游走分布](https://i.stack.imgur.com/iXJ89.png)
很明显,尽管表面相似,这些代码片段在做非常不同的事情。量子游走与经典随机游走不同。这种差异在某些算法中很有用。