A controlled-X gate applies the X transformation to a target qubit only when the control qubit contains 1. In a state-vector simulator, this means selecting amplitude pairs whose binary outcomes have a 1 at the control position, then applying X to the target position. section 4.4 section 4.4.1
Listing 4.5 Applying controlled gate transformations to a state
def is_bit_set(m, k):
return m & (1 << k) != 0
def c_transform(state, c, t, gate):
n = int(log2(len(state)))
for (k0, k1) in filter(lambda p: is_bit_set(p[0], c),
pair_generator(n, t)): #1
process_pair(state, gate, k0, k1) #2
The implementation detects whether a control bit is set, filters the target-related outcome pairs, and processes only those pairs with the selected gate. section 4.4.1
The state-vector operation follows a compact pattern:
- Represent each basis outcome as an integer whose binary digits identify qubit values. section 4.4.1
- Generate pairs of outcomes that differ at the target qubit. section 4.4
- Keep only pairs whose control-qubit digit is 1, then recombine each pair using X. section 4.4.1
Applying CX in a Python simulator
For a three-qubit state, calling c_transform(state, 1, 2, x) uses qubit 1 as the control and qubit 2 as the target. The amplitudes for outcomes 2 and 6 swap, as do those for 3 and 7; outcomes whose control bit is 0 remain unchanged. section 4.4.1
At circuit level, cx(c, t) records the gate, target, and control in a QuantumTransformation. Running the QuantumCircuit applies the queued transformations to its state amplitudes. section 4.5.2
