3
$\begingroup$

The c_if instruction can be used to make the result of a measurement saved to a classical register adjust whether a gate is or is not performed. How does the c_if instruction obtain the measurement result from the classical register and determine whether it meets the conditions? enter image description here

Like in the picture, how does c_if instruction get the measurement result in creg_c?

$\endgroup$
2
  • $\begingroup$ I'm not sure I understand your question. The line circ.measure(qreg_q[0], creg_c[0]) measures the qubit qreg_q[0] and stores the result in the classical bit creg_c[0]. Since this bit is classical, it is easy for a computer to read it to know whether the gate should be applied. $\endgroup$
    – Tristan Nemoz
    Sep 1, 2022 at 10:33
  • $\begingroup$ If instead of appling a gate based on the value of creg_c[0], I want to do a classical addition based on the value of creg_c [0], for example, if the value of creg_c [0] is 1, calculate a = a +1. How does that work? $\endgroup$ Sep 2, 2022 at 2:20

1 Answer 1

1
$\begingroup$

The complete version of your example is this:

from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit

qreg_q = QuantumRegister(2, name='q')
creg_c = ClassicalRegister(1, name='c')
circuit = QuantumCircuit(qreg_q, creg_c)

circuit.h(qreg_q[0])
circuit.measure(qreg_q[0], creg_c[0])
circuit.x(qreg_q[1]).c_if(creg_c, 0)
circuit.draw('mpl')

enter image description here

The value of c is a flip coin of 1 or 0. If it is one, X will be applied to the other qubit.

If based on the classical value of c, you want to perform a classical operation, like a = a +1, then no operation is performed on the quantum circuit.

You can move the quantum result to your classical Python world with execute

from qiskit import BasicAer, execute

qreg_q = QuantumRegister(1, name='q')
creg_c = ClassicalRegister(1, name='c')
circuit = QuantumCircuit(qreg_q, creg_c)

circuit.h(qreg_q[0])
circuit.measure(qreg_q[0], creg_c[0])

result = execute(circuit, BasicAer.get_backend('qasm_simulator'), shots=1).result().get_counts()

a = 3
if result.get('0', False):
    a = a + 1
print(a)
$\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.