1
$\begingroup$

This question is perhaps a bit unusual as I am not complaining that my code doesn't compile but rather that it compiles ;)

Consider the following code:

%%qsharp

open Microsoft.Quantum.Intrinsic;
open Microsoft.Quantum.Diagnostics;
open Microsoft.Quantum.Math;
open Microsoft.Quantum.Arrays;

operation AlgoTest() : Result[]  {
    let n=3; // Number of qubits
    use q = Qubit[n];
    mutable resultArray = [Zero, size = 3];
    H(q[0]);
    H(q[1]);
    H(q[2]);
    CNOT(q[0],q[1]);
    H(q[3]); // This line should make the compilation crash but it doesn't

    for i in IndexRange(q) {
        set resultArray w/= i <- M(q[i]);
    }
    return resultArray;
}

After that, I call the Azure resource estimator:

result = qsharp.azure.execute(AlgoTest)

To my surprise, the code compiles and gives me a resource estimate. However, it shouldn't be able to do it, as I initialized three qubits, and I applied a Hadamard on the inexistent fourth one (when I write H(q[3])).

The fact that it does compile makes me worry I do not understand what the code is actually doing.

Am I correctly understanding that it initializes 3 qubits in $|0\rangle$ (the Qubit[n] creates 3 qubits initialized in $|0\rangle$), applies Hadamard on each of them, followed by a CNOT between qubit 0 and 1, followed by a Hadamard on an inexistent qubit (the fourth one, labelled as 3), and all the qubits are finally measured in the computational basis?

$\endgroup$

1 Answer 1

2
$\begingroup$

Array index being out of bounds is a runtime error, not a compile-time error. In general case, the Q# compiler doesn't have all information it would need to detect an attempt to access a non-existent array element at compile time (array dimensions and indices accessed can depend on input parameters and other values defined only at runtime). Most compilers treat this type of error as runtime one, and don't attempt to check for it at compile-time. Q# simulator, which actually simulates program execution and checks for this error, would throw a runtime error at this point.

Since resource estimator doesn't fail here, it doesn't check for this type of errors. It is generally a good idea to write the code so that the small problem instances can run on a simulator, to verify the results and catch the errors, and then, once you're convinced that your code is correct, use resource estimator to evaluate the resources required to run the large problem instances.

$\endgroup$

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.