The first Q# code example provides a method "Set" that is written as follow (link):
operation Set (desired: Result, q1: Qubit) : ()
{
body
{
let current = M(q1);
if (desired != current)
{
X(q1);
}
}
}
This method set a qubit to a desired value. To do so, the qubit value is measured, and if the value is different than expected, the qubit state is "swapped".
But in quantum physics you cannot measure a particle without destroying it. Here is a quote of the book "Quantum Computation and Quantum Information":
... measurement changes the state of a qubit, collapsing it from its superposition of |0> and |1> to the specific state consistent with the measurement result. For example, if measurement of |+> gives 0, then the post-measurement state of the qubit will be |0>.
But using Q# you can measure a qubit and continue using it.
Why Q# langage allows us to realize an operation that is impossible in reality ?
Thank you by advance for answers.
I think it might be helpful to look back at your quote from Nielsen and Chuang:
For example, if measurement of |+⟩ gives 0, then the post-measurement state of the qubit will be |0⟩.
That is, the qubit is not destroyed by the measurement, but in order for quantum mechanics to be consistent, its state immediately following the measurement must agree with what we measured (this consistency requirement is sometimes informally called a "collapse").
In your Q# example, if we get a Zero
from the call to the M
operation, then we know that the qubit is in the |0⟩ state, precisely as described by Nielsen and Chuang.
On the other hand, if we get a One
from the call to M
, we know that the qubit is in the state |1⟩ = X |0⟩, such that we need to apply another X gate to get back to |0⟩.
(Note: if your qubits are stored as photons, then the discussion might well look very different — it's very hard to measure a photon without absorbing it into a material. It can be done using quantum nondemolition measurements, but that's another topic entirely. Q# assumes that qubits can be measured in the way that your quote from Nielsen and Chuang describes, rather than measured as photon absorption.)
With that as context, Q# is carefully designed to only allow measurements that could be realized in experimental practice.
Nonetheless, it's often very helpful to be able to use classical simulators to probe the state of some qubits in a way that wouldn't be possible on an actual quantum device.
There are two primary ways that you can do this in Q#.
First, you can use assertions like AssertQubit
to write unit tests that fail if the qubit isn't in the expected state.
Second, you can use the functions in the Microsoft.Quantum.Diagnostics
namespace to ask the simulator to dump what diagnostic information it has, such as the state it's using the represent the qubits used by your Q# program.
On actual hardware, the diagnostic information may look very different.