When initially writing an operator in Q#, I often want to see intermediate values of registers during the computation. This allows me to check that I haven't made mistakes. For example, if I was writing an addition circuit I would input a computational basis state and print out the computational basis states of qubits at particular key points.

I am not aware of a way to do this conveniently. If I print out the qubits like Message($"{qubit}") then I get their IDs instead of their values. That makes sense. I have to do a measurement to access their value. But if I do a measurement, then Q# will e.g. not automatically generate an adjoint operation and this tends to cause compilation failures. Also, I don't actually want to perform a measurement (which may have side effects) I just want to peek at the simulator state.

(I originally thought I could package the concept of "peeking" at a value into an operation that did a hidden measurement, which would have resolved the issue. But Q# doesn't allow operations with an adjoint to have a return type.)

Is there some built-in way to get at the computational basis value of some qubits, and print it to the console during simulation under the Toffoli simulator?


1 Answer 1


For Toffoli simulator in particular, DumpRegister will provide this information. For example, the following code

operation XorTest() : Bool {
    using ((a, b) = (Qubit[2], Qubit[2])) {
        // initialize: a = 1, b = 2
        ApplyPauli([PauliI, PauliX], a);
        ApplyPauli([PauliX, PauliI], b);
        // check initialization
        Message("a = ");
        DumpRegister((), a);
        Message("b = ");
        DumpRegister((), b);
        // calculate a ⊕ b and write it to b
        CNOT(a[0], b[0]);
        CNOT(a[1], b[1]);
        // check result: a ⊕ b = 3
        Message("a xor b = ");
        DumpRegister((), b);
    return true;

will print the following result (and throw an exception in the end because the qubits are released not in zero state):

a =
0:      False
1:      True
b =
2:      True
3:      False
a xor b =
2:      True
3:      True

The numbers before values are qubit ids.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.