12.5 An intro to QC programming
Source: Ideas from Computational Physics (Landau, Páez, Bordeianu), §12.5–12.5.1. Original sketches — do not paste textbook
Hadamard.py/CirqSwap.pydumps. Continues 12.4b. Labs: 12.5b.
Qubits and gates become circuits (programs). Cirq is a Python library for writing, simulating, and optimizing those circuits. Graded work on this site uses pure-Python amplitude / bit locks (no Cirq in the sandbox). Run the sketches below in a local conda/venv when you want the real simulator.
Install (local)
python -m pip install --upgrade pip
python -m pip install cirq
# or: conda install -c conda-forge cirq
First circuit: Hadamard on
# hadamard_sketch.py — structure only (run locally with Cirq)
import cirq
circuit = cirq.Circuit()
q = cirq.GridQubit(0, 0)
circuit.append(cirq.H(q))
sim = cirq.Simulator()
print(circuit)
print(sim.simulate(circuit)) # ≈ 0.707|0⟩ + 0.707|1⟩
Matches
Two Hadamards = identity
. Append a second cirq.H(a) on a NamedQubit('a'); the statevector returns to .
X then H →
X maps ; then H yields , an eigenstate of with eigenvalue .
Measure: X, Z, H + shots
Measurement is not unitary. Append cirq.measure(a, key='result'), then sim.run(circuit, repetitions=1000) and plot a histogram. Ideal amplitudes after on are equal magnitude (), so counts of and each sit near (noise → slight tilt — Figure 12.3).
Two qubits: LineQubit, SWAP, CNOT
q0, q1 = cirq.LineQubit.range(2)
circuit.append(cirq.X(q0)) # |10⟩ if start |00⟩
circuit.append(cirq.Z(q1)) # phase only on |1⟩ of q1
# expected state |10⟩
SWAP exchanges the two lines: after on q0 you get .
CNOT(control=q0, target=q1): with input, flips the target → .
Three qubits: Toffoli
q0, q1, q2 = cirq.LineQubit.range(3)
circuit.append(cirq.X(q0))
circuit.append(cirq.Toffoli(q0, q1, q2)) # flips q2 only if q0=q1=1
With only q0 flipped, controls are not both , so the target stays put (e.g. or depending on q2’s prep). Flip both controls to see .
12.5.1 Half and full adders
Half-adder (sum + carry)
Classical: sum , carry . Quantum recipe on three lines (q2 starts at ):
- Toffoli(q0, q1, q2) → write carry into q2
- CNOT(q0, q1) → write sum into q1
Lab: wire the half-adder
Check truth table: → sum , carry ; and → sum , carry .
Full adder
A full adder folds in a carry-in. One Cirq-shaped skeleton (four qubits): cascade Toffoli / CNOT so that after prep of q0,q1,Cin the sum and Cout match classical binary addition. Fill the table in labs for all four input pairs (Cin fixed or varied).
| q0 | q1 | Cin | Sum | Cout |
|---|---|---|---|---|
| … | … | … | ||
| … | … | … | ||
| … | … | … | ||
| … | … | … |
Takeaway
| Goal | Cirq idea |
|---|---|
| Superposition | H on GridQubit / NamedQubit |
two H on same line | |
| Statistics | measure + run(..., repetitions=) |
| Entangle / flip | CNOT, SWAP, Toffoli |
| Add | Toffoli carry + CNOT sum |
Cirq / adders
1 / 3Two Hadamard gates on |0⟩ yield…
Pick an answer to see if you are right.
Next: 12.5b Cirq labs · 12.6 IBM Quantum.