oreilly-qc / oreilly-qc.github.io

Code samples for Programming Quantum Computers, from O'Reilly Media
135 stars 62 forks source link

Usage of qc.write #43

Open fernandotenorio opened 2 years ago

fernandotenorio commented 2 years ago

The code below writers a zero into qubit 0x8. Is this a bug or I'm I missing something? It is not clear how qc.write works when the 2nd arg is provided.

qc.reset(6);
qc.write(1, 0x8);

thanks.

machinelevel commented 2 years ago

Hi there! I see why this is unclear; in the case of qc.write(value, mask), if the mask parameter is used, then it indicates the mask of qubits which should be written, and each bit in value will be written to the corresponding bit in mask.

So in your example, qc.write(1, 0x8) should be qc.write(0x8, 0x8), so that the fourth qubit (which is set in the mask) will receive the 1 value. While it may seem more intuitive to use qc.write(1, 0x8), this causes trouble if you choose to write multiple bits, which may be non-contiguous.

Option 1:

Match the value bits with the mask bit, as mentioned above...

qc.write(0x8, 0x8)

Option 2:

If you want a slightly more intuitive way to do this, the qint data type is a thin wrapper which lets you treat groups of qubits as integers, so you could do this:

qc.reset(6);              // allocate six qubits
var a = qint.new(3, 'a'); // a three-qubit int
var b = qint.new(1, 'b'); // a one-qubit int
b.write(1);               // write 1 to the fourth qubit
var result = b.read();    // read the result as a digital bit
qc.print('b.read() = ' + result);

This writes the qubit as expected: image ...and prints b.read() = 1.

...does that make sense and clear things up a bit?

rgobbel commented 1 year ago

I was having the same problem. This does indeed clear things up. IWBN to put this into the documentation.