43 min read

> "A language that doesn't affect the way you think about programming is not worth knowing."

Learning Objectives

  • Describe what a quantum program is as an artifact — a circuit, a compilation target, and a sampling procedure — and name what a quantum computer returns to you.
  • Name the five major quantum programming frameworks, state the design bet each one makes, and explain why the field has not converged on one.
  • Trace the quantum software stack from application code down to control pulses, and map each layer onto its classical analogue.
  • Explain the four properties — probabilistic output, no-cloning, measurement collapse, and entanglement as a resource — that make quantum programming structurally different from classical programming.
  • Give an honest account of what quantum hardware can and cannot do today, and identify the class of claims that should make you skeptical.
  • State the goal, success criterion, and architecture of the book's running project.

Chapter 1: The Quantum Programming Landscape

"A language that doesn't affect the way you think about programming is not worth knowing." — Alan Perlis, Epigrams on Programming, 1982

Overview

There are five major quantum programming frameworks in wide use. There is no consensus about which one you should learn, and no serious prospect of consensus arriving soon.

That fact is the best possible introduction to the state of quantum programming, and it is why this book begins with a survey rather than with code. The frameworks disagree about what a quantum program is — not superficially, in the way that Python and Ruby disagree about syntax, but structurally, in the way that C and Prolog disagree about what computation looks like. One framework models a program as a list of gates. Another models it as a schedule of simultaneous operations on physically located qubits. Another models it as a differentiable function. Another gives quantum data a type system and quantum operations their own control flow. Understanding those disagreements is the fastest route to understanding the domain, because each framework is a distilled argument about what matters.

This chapter is the map. By the end you will know what a quantum program actually is as an artifact, what the five frameworks are and what each one bets on, how the software stack is layered from your Python file down to the microwave pulses that manipulate physical qubits, and — most importantly — the four specific properties of quantum computation that will break the programming instincts you have spent your career developing.

You will also get an honest accounting of what today's machines can do, which is much less than the press coverage implies and much more than the backlash implies.

In this chapter, you will learn to:

  • Describe what a quantum program is: a quantum circuit, compiled to a hardware instruction set, executed many times, returning a distribution of bitstrings.
  • Name the five frameworks — Qiskit, Cirq, PennyLane, Q#, and Amazon Braket — along with OpenQASM, and articulate the design bet each one makes.
  • Trace the quantum software stack from application down through circuit, transpiler, and pulse layers to hardware, and map each layer onto its classical analogue.
  • Explain the four structural differences: probabilistic output, the no-cloning theorem, measurement collapse, and entanglement as a computational resource.
  • State clearly what current hardware can and cannot do, and recognize the specific shapes of overclaiming that are endemic to this field.
  • Understand the book's running project and its success criterion.

Learning Paths

How to read this chapter by track. - 🔰 Beginner — read §1.1, §1.4, and §1.5 carefully; skim §1.2 and return to it after Chapter 13, when the framework differences will mean more. - 🔬 Researcher — §1.3 (the stack) and §1.5 (capabilities) are the ones that will shape your experimental design. §1.2 matters when you choose where to publish reproducible code. - 🤖 Quantum ML — §1.2's PennyLane paragraph is your future; §1.4's discussion of what measurement returns explains why quantum models are trained the way they are. - 🏗️ Quantum Engineer — §1.3 is the chapter for you and it is worth a second read; the stack diagram is the mental model that Parts II and V elaborate. - 🔐 Security — §1.5 is the section to internalize. The gap between "Shor's algorithm exists" and "RSA is broken" is a resource-estimate question, and this section frames it.


1.1 What a Quantum Program Actually Is

Strip away the physics for a moment and look at the artifact.

A quantum program, as you will write it, is a quantum circuit: an ordered sequence of operations applied to a fixed number of qubits, ending in measurements that produce classical bits. Here is one, complete, in Qiskit:

from qiskit import QuantumCircuit

qc = QuantumCircuit(2, 2)   # 2 qubits, 2 classical bits
qc.h(0)                     # put qubit 0 into superposition
qc.cx(0, 1)                 # entangle qubit 1 with qubit 0
qc.measure([0, 1], [0, 1])  # measure both into the classical bits

print(qc.draw())
     ┌───┐     ┌─┐
q_0: ┤ H ├──■──┤M├───
     └───┘┌─┴─┐└╥┘┌─┐
q_1: ─────┤ X ├─╫─┤M├
          └───┘ ║ └╥┘
c: 2/═══════════╩══╩═
                0  1

That is a complete quantum program. It is four lines. It is also — this will matter — a Bell state preparation, the single most important two-qubit circuit in the field, and you will meet it again in Chapter 2, in Chapter 4, and in essentially every discussion of noise in this book.

Three things about this artifact are worth noticing immediately.

It is a fixed-size, straight-line object. There are no loops in that circuit, no recursion, no dynamic allocation. The number of qubits is fixed at construction. The gate sequence is known before execution. Modern hardware does support limited classical control flow mid-circuit — that is Chapter 9's subject, and it is genuinely useful — but the default and dominant model is a static circuit. This is much closer to writing a hardware description than to writing a Python script, and it is one reason the ergonomics feel strange at first.

It compiles. You do not run that circuit. You run something else — a rewritten version of it, expressed only in the gates the target hardware physically implements, mapped onto specific physical qubits, with extra operations inserted to move information between qubits that are not physically connected. That rewriting step is called transpilation and it is important enough to get Chapter 10 to itself. On a real device, the four-line circuit above typically becomes a longer sequence in a different gate set before anything executes.

It returns a distribution, not a value. This is the deepest of the three. Run that circuit once and you get two classical bits: 00 or 11, with roughly equal probability, and you cannot predict which. Run it a thousand times — a thousand shots — and you get counts:

{'00': 508, '11': 492}

The output of a quantum program is a histogram. Every quantum program. Extracting a definite answer from a histogram is a statistical problem, and it is a problem you now own. Chapter 5 is devoted to it.

⚛️ The Physics Underneath — What the qubits are doing here.

A classical bit is 0 or 1. A qubit's state is a pair of complex numbers $(\alpha, \beta)$ — called amplitudes — subject to $|\alpha|^2 + |\beta|^2 = 1$. We write the state as $\alpha|0\rangle + \beta|1\rangle$. It is not "0 and 1 at the same time," a phrase that has done more damage than any other sentence in popular science; it is a vector in a two-dimensional complex space, and the two numbers matter, including their relative phase.

The H gate takes $|0\rangle$ to $\frac{1}{\sqrt{2}}(|0\rangle + |1\rangle)$ — equal amplitude on both outcomes. The CNOT then correlates the second qubit with the first, producing $\frac{1}{\sqrt{2}}(|00\rangle + |11\rangle)$. Measurement returns 00 with probability $|1/\sqrt{2}|^2 = 1/2$ and 11 with the same, and 01 and 10 with probability exactly zero.

Everything in that paragraph gets a full treatment in Chapters 3 and 4. You need none of it to proceed.

The three questions a quantum program can answer

Because the output is a distribution, there are really only three shapes of question you can ask a quantum computer, and every algorithm in this book is one of them.

"What is the most likely outcome?" Some algorithms concentrate almost all the probability on a single bitstring, which encodes the answer. Grover's search (Chapter 21) and Shor's period finding (Chapter 23) work this way. You sample a few hundred times, take the mode, and verify classically. Verification matters: Shor's algorithm produces a candidate factor that you check by dividing, which converts a probabilistic quantum result into a certainty.

"What is the expectation value of this observable?" Some algorithms encode the answer in an average rather than in any single outcome. Variational algorithms — VQE, QAOA, essentially all of quantum machine learning — ask for $\langle\psi|H|\psi\rangle$, a single real number estimated from many measurements. This is the pattern that dominates near-term quantum computing, and it is why Qiskit's interface has a dedicated Estimator primitive alongside the Sampler primitive. Chapter 7 §7.6 is built around this distinction.

"What is the whole distribution?" Occasionally the distribution itself is the object of interest — in sampling problems, in some simulation tasks, and in the random-circuit-sampling experiments used for hardware benchmarking. This is the rarest case and the one with the least clear practical application.

Knowing which of these three you are asking determines your shot count, your error mitigation strategy, and your choice of primitive. Beginners frequently pick the wrong one — asking for a full distribution when they need an expectation value costs enormously more shots for a worse answer.

1.2 Five Frameworks, and Why There Are Five

Now the survey. Each framework below gets a paragraph on its bet, a paragraph on its shape, and a short code sample of the same program — the Bell state from §1.1 — so you can see the differences with your own eyes rather than take my word for them.

Do not try to learn five frameworks now. Read this section to build a mental index; the depth comes in Parts II and III.

Qiskit (IBM) — the circuit-and-compiler bet

The bet: quantum programming is circuit construction plus serious compilation, and the way to win is to have the best compiler and the most accessible hardware.

Qiskit is the most widely used quantum SDK by a wide margin, and it is this book's primary framework. It is Python, open source, and — decisively for a learner — it is the front door to free access to real IBM quantum processors. That last point is not a small thing. You will run code on physical quantum hardware in Chapter 2 because IBM decided in 2016 to put quantum processors on the open internet and has kept them there.

Qiskit's design center is the QuantumCircuit object and the transpiler that lowers it to hardware. Its transpiler is the most mature in the field: multiple optimization levels, pluggable passes, several layout and routing algorithms, and a genuinely good story for hardware-aware compilation (Chapters 10, 28, 29). Its Runtime service adds a managed execution layer with the Sampler and Estimator primitives, session-based execution, and built-in error mitigation (Chapters 7, 12, 13).

# Qiskit
from qiskit import QuantumCircuit

qc = QuantumCircuit(2, 2)
qc.h(0)
qc.cx(0, 1)
qc.measure([0, 1], [0, 1])

Where it is weakest: the API has churned hard. Qiskit 1.0 (February 2024) removed execute(), the function used in nearly every tutorial written before that date, and removed QuantumCircuit.qasm(). Qiskit 2.0 removed the Pulse module entirely. This churn is the single biggest source of frustration for new quantum programmers, and this book handles it with 🗝️ Version Note callouts throughout.

🗝️ Version Note — The two API removals you will trip over immediately.

Pre-1.0 tutorials contain this pattern constantly:

python from qiskit import execute, Aer # both broken in Qiskit 1.0+ backend = Aer.get_backend("qasm_simulator") result = execute(qc, backend, shots=1024).result()

execute() no longer exists. Aer moved to the separate qiskit_aer package. The modern equivalent is:

```python from qiskit_aer import AerSimulator from qiskit import transpile

sim = AerSimulator() result = sim.run(transpile(qc, sim), shots=1024).result() print(result.get_counts()) ```

Similarly, qc.qasm() is gone; use qiskit.qasm3.dumps(qc) or qiskit.qasm2.dumps(qc) (Chapter 6).

When you find quantum code on the internet — and you will, constantly — check its date before you check your own understanding. Half the code out there does not run.

Cirq (Google) — the scheduling bet

The bet: the physical structure of the machine is part of the program, and hiding it is a mistake.

Cirq makes two things explicit that Qiskit abstracts. First, qubits are located: a GridQubit(3, 4) is a specific position on a two-dimensional lattice, matching the physical layout of Google's Sycamore and Willow processors. Second, a circuit is a sequence of Moments — time slices in which several operations happen simultaneously — rather than a flat list of gates. Timing is first-class.

# Cirq
import cirq

q0, q1 = cirq.LineQubit.range(2)
circuit = cirq.Circuit([
    cirq.H(q0),
    cirq.CNOT(q0, q1),
    cirq.measure(q0, q1, key="result"),
])

That design pays off in NISQ-era research, where knowing exactly which operations run in parallel — and therefore which qubits sit idle accumulating decoherence — is scientifically important. Cirq is the research community's framework as much as it is Google's, and much of the important NISQ algorithms literature ships Cirq code.

Where it is weakest: hardware access. Google's processors are not generally available the way IBM's are, so Cirq users mostly simulate or run on third-party devices through adapters.

PennyLane (Xanadu) — the differentiability bet

The bet: a quantum circuit is a differentiable function, and everything follows from that.

PennyLane's central object is the QNode — a quantum circuit wrapped so that it behaves like an ordinary differentiable Python function. You can take its gradient. You can pass it to a PyTorch optimizer. You can put it inside a torch.nn.Module as a layer. The gradients are exact, computed by the parameter-shift rule rather than by backpropagation, and the whole design falls out of that one idea.

# PennyLane
import pennylane as qml

dev = qml.device("default.qubit", wires=2, shots=1024)

@qml.qnode(dev)
def bell():
    qml.Hadamard(wires=0)
    qml.CNOT(wires=[0, 1])
    return qml.counts()

PennyLane is also aggressively hardware-agnostic: through its plugin system, the same QNode runs on its own simulators, on IBM hardware, on Braket devices, or on Cirq. That makes it a good choice when you want to compare backends without rewriting.

Where it is weakest: if you are not doing anything gradient-flavored, the abstraction is overhead. For circuit construction and hardware compilation, Qiskit gives you more control.

Q# (Microsoft) — the language bet

The bet: quantum programming deserves a real language, not a library embedded in Python.

Q# is the only serious purpose-built quantum programming language in wide use. It has a type system that distinguishes Qubit from Result from Pauli. It has scoped qubit allocation (use q = Qubit()), so the compiler knows a qubit's lifetime. It automatically generates the adjoint (inverse) and controlled variants of your operations — which is a genuinely large convenience, because uncomputation is everywhere in quantum algorithms and writing every inverse by hand is both tedious and a reliable source of bugs. It has within/apply syntax for exactly that compute–uncompute pattern.

// Q#
operation Bell() : (Result, Result) {
    use (q0, q1) = (Qubit(), Qubit());
    H(q0);
    CNOT(q0, q1);
    let result = (M(q0), M(q1));
    ResetAll([q0, q1]);
    return result;
}

Q# also ships the Azure Quantum Resource Estimator, which is the most sobering tool in the field: give it an algorithm and it tells you how many physical qubits and how much runtime a fault-tolerant implementation would require. Chapter 15 uses it, and Chapter 23 uses its output to put a number on "when does RSA break."

Where it is weakest: the ecosystem is smaller, and being a separate language means less integration with the Python data-science stack — though the qsharp package makes Q# callable from Python, which is how most people use it.

Amazon Braket (AWS) — the portability bet

The bet: the interesting variable is the hardware, and what you want is one SDK that reaches all of it.

Braket is less a philosophy than a marketplace with a decent SDK. Through it you reach superconducting processors, trapped-ion processors from IonQ, and neutral-atom processors from QuEra — three physically different technologies with genuinely different error profiles, gate sets, and connectivity. Running the same circuit on a trapped-ion device and a superconducting device and comparing the results teaches you something you cannot learn any other way, and Chapter 17 does exactly that.

# Amazon Braket
from braket.circuits import Circuit
from braket.devices import LocalSimulator

circuit = Circuit().h(0).cnot(0, 1)
result = LocalSimulator().run(circuit, shots=1024).result()
print(result.measurement_counts)

Where it is weakest: it costs money. Braket bills per task and per shot on real hardware. Chapter 17 gives you the cost model explicitly, and every Braket example in this book also runs on the free local simulator.

OpenQASM — the lingua franca

Not a framework: an assembly language. OpenQASM is a textual representation of a quantum circuit, at roughly the level of abstraction of classical assembly. Frameworks compile to it, hardware consumes it, and — crucially for you — it is the interchange format between frameworks.

// OpenQASM 3
OPENQASM 3.0;
include "stdgates.inc";

qubit[2] q;
bit[2] c;

h q[0];
cx q[0], q[1];
c[0] = measure q[0];
c[1] = measure q[1];

You will not write production code in QASM, in the same way that you do not write production code in x86 assembly. You will read it constantly, because it is how you see what the transpiler did. Chapter 6 teaches it and Appendix F is the reference.

So why five?

Because the field is young and nobody has been proven right yet.

The classical analogy is genuinely apt. In 1960 there were dozens of programming languages, each representing a different theory of what programming was: FORTRAN for numerics, COBOL for business records, LISP for symbolic manipulation, ALGOL for expressing algorithms precisely. Convergence happened later, and it happened partly because hardware converged — the von Neumann architecture won, and languages could stop being machine-specific.

Quantum hardware has not converged. Superconducting qubits, trapped ions, neutral atoms, photonics, and spin qubits are all live technologies with different gate sets, connectivity, coherence times, and error mechanisms. IBM's heavy-hexagonal lattice and IonQ's all-to-all connectivity are not minor variations; they demand different compilation strategies. As long as the hardware is diverse, the software will be too.

There is a second reason, less often stated: the frameworks are backed by companies competing for a market that does not yet exist. Qiskit, Cirq, Braket, and Q# are open source, and they are also strategic assets. That is not cynicism — the open-sourcing has been genuinely generous and the field is better for it — but it does explain why the incentive to converge is weak.

🔬 Honest Assessment — Which framework should you actually learn?

Learn Qiskit first. It has the largest community, the best free hardware access, and the most complete tooling, so you will find answers when you get stuck. That is worth more than any design elegance when you are learning.

Then learn a second one, chosen by what you do: PennyLane if you are doing anything gradient-based, Cirq if you are doing NISQ algorithm research or reading the literature, Q# if you care about resource estimation or large algorithm design, Braket if you need hardware diversity.

Do not try to learn all five in parallel. Do learn to read all five, which is a much lower bar and is what Chapter 18 is for.

1.3 The Quantum Software Stack

Here is the layered picture. Every quantum program passes through all of these layers, whether or not you interact with them directly.

┌───────────────────────────────────────────────────────────────────┐
│  APPLICATION           your program: "find the ground state of H2" │
│                        Qiskit Nature, PennyLane, your own code     │
├───────────────────────────────────────────────────────────────────┤
│  ALGORITHM             VQE, QAOA, Grover, Shor                     │
│                        parameterized circuits + classical loop     │
├───────────────────────────────────────────────────────────────────┤
│  CIRCUIT               QuantumCircuit: gates on abstract qubits    │
│                        the layer you write in                      │
├───────────────────────────────────────────────────────────────────┤
│  INTERMEDIATE REP.     OpenQASM 3 — the portable text form         │
├───────────────────────────────────────────────────────────────────┤
│  TRANSPILER            decompose to basis gates; map logical →     │
│                        physical qubits; insert SWAPs for routing;  │
│                        optimize   ← Chapters 10, 28, 29            │
├───────────────────────────────────────────────────────────────────┤
│  SCHEDULE / PULSE      gates → timed microwave/laser pulses        │
│                        calibration lives here   ← Chapter 31       │
├───────────────────────────────────────────────────────────────────┤
│  CONTROL ELECTRONICS   arbitrary waveform generators, mixers,      │
│                        digitizers, FPGA sequencers                 │
├───────────────────────────────────────────────────────────────────┤
│  QUANTUM PROCESSOR     physical qubits at ~15 millikelvin          │
│                        (or trapped ions, or neutral atoms)         │
└───────────────────────────────────────────────────────────────────┘

The classical analogy is close enough to be useful and worth stating precisely:

Quantum layer Classical analogue
Application Your application code
Algorithm A library or algorithm implementation
Circuit Source code in a systems language
OpenQASM An intermediate representation — LLVM IR, or assembly
Transpiler The compiler backend: instruction selection, register allocation, scheduling
Pulse Microcode
Control electronics The processor's front end
QPU The silicon

The analogy has one important defect. In classical computing, a compiler's job is to produce equivalent code; performance varies, correctness does not. In quantum computing, the transpiler's output determines whether you get an answer at all, because every inserted gate adds error and every nanosecond of added duration lets the qubits decohere further. A poorly transpiled circuit does not run slowly. It returns noise.

That is why Part II gives the transpiler an entire chapter, and why Part V gives hardware-aware programming another.

⚙️ Under the Transpiler — A preview of the gap.

The four-line Bell state from §1.1 uses H and CNOT. Current IBM processors do not physically implement either one. Their native two-qubit gate is ECR (echoed cross-resonance) or CZ, depending on the device generation, and their single-qubit basis is typically {rz, sx, x} — a $Z$-rotation, a square-root-of-$X$, and $X$.

So the transpiler rewrites H as a short sequence of rz and sx, and rewrites CNOT in terms of ECR plus single-qubit corrections. A two-gate circuit becomes six or seven physical operations. That expansion factor is typical, it compounds with circuit size, and it is the reason "how many gates does my algorithm need" is a question with two very different answers.

Chapter 10 shows you the exact expansion for your device, and Chapter 28 shows you how to fight it.

Where the layers meet you

Most of your time will be spent at the circuit layer, which is the right place to be. But you will drop down more often than a classical developer drops into assembly:

  • Down to OpenQASM whenever you need to move a circuit between frameworks or archive it in a form that will still parse in five years (Chapter 6).
  • Down to the transpiler whenever a circuit that works in simulation fails on hardware, which is most of the time at first (Chapters 10, 26).
  • Down to calibration data whenever you need to choose which physical qubits to use, which turns out to matter enormously (Chapter 29).
  • Down to pulses rarely, and mostly if you work at a hardware company or do quantum control research (Chapter 31).

And you will move up to the algorithm and application layers when you use packages like Qiskit Nature, which take a molecule and hand you a Hamiltonian. Chapter 36 does this and is careful to show you what the package is doing on your behalf, because a library that hides the physics from you also hides the bugs.

1.4 The Four Things That Make This Different

Everything that follows in this book is easier if you internalize four properties now. Each one breaks a specific instinct you have as a classical programmer.

1. Output is probabilistic — by design, not by defect

The broken instinct: assert f(x) == expected.

A correct quantum program returns different answers on different runs. This is not flakiness to be engineered away; it is the computational model. The Bell circuit returns 00 about half the time and 11 about half the time, and any run in which it returned only 00 a thousand times in a row would indicate a broken device.

The consequences run deep:

  • Testing must become statistical. You cannot assert equality; you assert that a distribution is consistent with an expected one, at some tolerance, with some number of samples. Chapter 27 builds this vocabulary.
  • Precision costs shots, quadratically. Estimating a probability to within $\epsilon$ requires on the order of $1/\epsilon^2$ shots. Ten times more precision costs a hundred times more runs. This single scaling fact governs the economics of near-term quantum computing, and Chapter 5 §5.4 derives it.
  • "It worked once" means nothing. A result from a single run is not a result.

2. You cannot copy a qubit — the no-cloning theorem

The broken instinct: backup = state; try_something(state); state = backup.

There is no operation that takes an unknown quantum state and produces two copies of it. This is a theorem, proved in a half-page in 1982, not an engineering limitation. It follows directly from the linearity of quantum mechanics.

Consequences:

  • No checkpointing. You cannot save a state before a risky operation and restore it. If you need a state again, you must prepare it again from scratch, which is why circuits are re-run rather than resumed.
  • No naive error correction. The classical trick of storing three copies and majority-voting is unavailable. Quantum error correction had to be invented from a different direction — encoding information nonlocally across many qubits — and Chapter 25 shows how.
  • Quantum key distribution works. The same theorem that blocks copying makes eavesdropping detectable, which is the entire basis of BB84 (Chapter 38). The limitation and the application are the same fact seen from two sides.

3. Measurement destroys what it measures

The broken instinct: print(state) # just to see what's happening.

Measuring a qubit in superposition collapses it to a definite value, permanently, and the rest of the computation proceeds from the collapsed state. There is no observation without disturbance.

This is the property that makes quantum debugging genuinely hard, and it is why Chapter 26 exists. The techniques that replace print are: simulate a small instance and inspect the full statevector classically; insert measurements deliberately and compare distributions to predictions; test subcircuits in isolation; and compare against analytically computed expectations. All four are indirect. None is as convenient as a print statement. Getting good at them is a large part of becoming competent here.

⚠️ Common Pitfall — Simulators let you cheat, and you should — carefully.

A simulator will let you read the full statevector at any point. This is the single most useful debugging tool you have, and Chapter 26 leans on it hard.

The trap is forgetting that it is a simulator privilege. Code that inspects the statevector cannot run on hardware, and an algorithm whose correctness argument depends on inspecting intermediate states is not a quantum algorithm. Use statevector inspection to debug; never let it into the algorithm.

4. Entanglement is a resource you spend

The broken instinct: treating variables as independent unless you deliberately combine them.

When qubits are entangled, they do not have individual states. The two-qubit Bell state $\frac{1}{\sqrt{2}}(|00\rangle + |11\rangle)$ cannot be written as "qubit 0 is in state $A$ and qubit 1 is in state $B$" for any $A$ and $B$. The state belongs to the pair.

Two practical consequences:

Entanglement is where the power comes from. An $n$-qubit state requires $2^n$ complex amplitudes to describe. Twenty qubits is a million amplitudes; fifty is a quadrillion. That exponential space is the resource quantum algorithms exploit — but only if the state is entangled. A product state of $n$ qubits is describable with $2n$ numbers and simulable on a phone.

Entanglement is also where the bugs come from. Qubits accidentally left entangled with ancillas are the most common source of quantum algorithms that mysteriously stop working. The interference that makes Grover's algorithm concentrate probability on the right answer requires the ancillas to be disentangled first — which is why uncomputation (Chapter 19 §19.6) is a discipline rather than an optimization.

📐 Math Aside — Why $2^n$, concretely.

One qubit: two amplitudes, $(\alpha_0, \alpha_1)$ for outcomes $|0\rangle, |1\rangle$.

Two qubits: four, for $|00\rangle, |01\rangle, |10\rangle, |11\rangle$.

$n$ qubits: $2^n$, one per bitstring. In code:

```python import numpy as np

for n in (1, 10, 20, 30, 40, 50): amplitudes = 2 ** n gib = amplitudes * 16 / 2**30 # complex128 = 16 bytes print(f"{n:2d} qubits: {amplitudes:>18,d} amplitudes {gib:>12,.3f} GiB") ```

text 1 qubits: 2 amplitudes 0.000 GiB 10 qubits: 1,024 amplitudes 0.000 GiB 20 qubits: 1,048,576 amplitudes 0.016 GiB 30 qubits: 1,073,741,824 amplitudes 16.000 GiB 40 qubits: 1,099,511,627,776 amplitudes 16,384.000 GiB 50 qubits: 1,125,899,906,842,624 amplitudes 16,777,216.000 GiB

Thirty qubits fits on a large workstation. Forty needs a supercomputer. Fifty is out of reach for exact statevector simulation on any machine that exists. That boundary — around 40 to 50 qubits — is why quantum hardware is interesting at all, and Chapter 11 explores the clever partial escapes (stabilizer and tensor-network simulation) that push it around without breaking it.

What the exponential state space does not buy you

That table is the most quoted fact in quantum computing, and the inference most often drawn from it is wrong. The wrong inference is: the machine holds $2^n$ values, so it tries $2^n$ possibilities at once. The table is real. The conclusion does not follow from it, and believing it will make every algorithm in Part IV look arbitrary to you.

Two facts kill it.

You get $n$ bits out per shot, not $2^n$ amplitudes. A 30-qubit register really does hold 1,073,741,824 complex amplitudes. Measure it and you receive thirty bits: one bitstring, drawn from a distribution you never got to see. The amplitudes exist. They are not addressable.

Reading them out is exponentially expensive. Normalization and global phase remove two real degrees of freedom from the $2^n$ complex amplitudes, leaving $2^{n+1} - 2$ real parameters. Pinning each of those to a resolution of $\epsilon$ takes at least $\log_2(1/\epsilon)$ bits of information, and a shot supplies at most $n$ bits. So the shot count has a floor:

$$N_{\text{shots}} \;\ge\; \frac{\left(2^{n+1} - 2\right)\log_2(1/\epsilon)}{n}$$

   qubits    real parameters    shots (floor, at epsilon = 0.01)
        2                  6                            1.99e+01
       10              2,046                            1.36e+03
       20          2,097,150                            6.97e+05
       30      2,147,483,646                            4.76e+08

★ At thirty qubits, merely reading the state out costs at least half a billion shots — and that is an information-theoretic floor, not an engineering estimate. It assumes you extract every bit a measurement can carry, and it ignores the basis changes real tomography needs. The true cost is worse.

So the state space is not a database you can query. It is a medium in which amplitudes interfere, and an algorithm's job is to arrange for the amplitudes on wrong answers to cancel before you look. Nothing else about the $2^n$ helps you.

📐 Math Aside — The proof that it is interference, not parallelism.

Chapter 21 runs Grover's algorithm on a 4-bit search space, $N = 16$, and measures the probability of getting the marked item after $k$ iterations:

text 3 iterations 0.9613 6 iterations 0.0204

Doing twice as much work made the right answer forty-seven times less likely. If the machine were evaluating all sixteen candidates in parallel and reporting the winner, that could not happen — more searching cannot destroy a found item. Interference can, and here it does.

The closed form says exactly how. Write $\sin\theta = 1/\sqrt{N}$. Each Grover iteration rotates the state by $2\theta$ in a two-dimensional plane, so after $k$ iterations

$$P(\text{marked}) = \sin^2\!\big((2k+1)\,\theta\big)$$

At $N = 16$ that is $\theta = \arcsin(1/4) = 0.25268$ rad:

text k (2k+1)*theta P(marked) 0 0.2527 0.0625 1 0.7580 0.4727 2 1.2634 0.9084 3 1.7687 0.9613 4 2.2741 0.5817 5 2.7794 0.1255 6 3.2848 0.0204

Both measured values fall out to four decimal places, and every intermediate row of that ladder appears in Chapter 21 §21.4's over-rotation table too. The rotation overshoots. At $k = 3$ the state sits near the top of the first arc; by $k = 6$ it has swung past and most of the way back down — below $P = 0.0625$, which is what you would get by guessing. Six iterations of a correct, noiseless implementation do measurably negative work. The iteration count is therefore not "as many as you can afford"; it is a specific number you compute in advance, and Chapter 21 §21.3 derives it as $k^\star = \big\lfloor (\pi/4)\sqrt{N} \big\rfloor$.

That formula is checkable against a second, independent measurement in the same chapter. A 20-bit search is $N = 2^{20} = 1{,}048{,}576$, and

$$\frac{\pi}{4}\sqrt{2^{20}} = 0.785398 \times 1024 = 804.2477 \;\longrightarrow\; 804$$

Chapter 21 runs 804 iterations. Not approximately — exactly the floor of the formula. And its reported cost of 229,944 T gates divides by 804 to give 286 T gates per iteration, with no remainder. The per-iteration cost is a constant; the iteration count carries all of the scaling.

Which is where the honesty comes in. Brute force over that space is 1,048,576 oracle calls and Grover is 804 — a factor of 1,304, an enormous saving. It is also quadratic, not exponential. $\sqrt{2^n} = 2^{n/2}$ is still exponential in $n$. Grover halves the exponent. It does not remove it, and Chapter 21 §21.7 is blunt about what that means for the "search a database" framing.

⚠️ Common Pitfall — "Quantum parallelism" as an explanation.

The phrase is not exactly false. A superposition really does carry amplitude on every input at once. It is useless as an explanation, because it predicts none of the behavior above. It does not predict that six Grover iterations are worse than three. It does not predict that only a quadratic speedup is available for unstructured search. It does not predict that getting the answer out is the bottleneck rather than computing it.

A better one-sentence model: a quantum computer builds interference patterns, and an algorithm is a recipe for making the wrong answers cancel. That version predicts all three, and it is the model Part IV is built on.

1.5 What You Can and Cannot Do Today

This section is the one to reread before you talk to a manager, a journalist, or a vendor.

The hardware, factually

Current quantum processors are in what is called the NISQ era — Noisy Intermediate-Scale Quantum, a term John Preskill coined in 2018 and which remains accurate. The defining characteristics: enough qubits to be beyond easy classical simulation, and far too much noise to run deep circuits or error correction at scale.

Concretely, and stated as orders of magnitude because specifics drift within months:

  • Qubit counts are in the hundreds to low thousands. IBM's Eagle processor (2021) has 127 qubits, Osprey (2022) 433, Condor (2023) 1,121; the Heron generation trades raw count for quality at 133 and 156. Google announced Willow, at 105 qubits, in December 2024. IonQ and Quantinuum operate trapped-ion systems with fewer qubits but higher fidelity and all-to-all connectivity.
  • Two-qubit gate error rates are in the range of a few parts per thousand on the best devices. That sounds small. It is not, because the failures compound: at 0.3% per gate, a circuit with 1,000 two-qubit gates completes with no gate error only about 5% of the time, and at 2,000 gates about 0.25%. Exercise 1.11 has you build the whole table, and the shape of it is the most important thing in this section.
  • Coherence times are on the order of tens to hundreds of microseconds for superconducting qubits, and gates take tens to hundreds of nanoseconds. So you get, very roughly, hundreds to a few thousand sequential operations before the state decays — a hard deadline that Chapter 29 teaches you to program against.
  • Error correction has been demonstrated below threshold — Google's Willow result in December 2024 showed that adding more physical qubits to a surface code patch decreased the logical error rate, which is the crucial scaling behavior. That is a genuine milestone. It is not the same as having a useful error-corrected computer, which requires roughly a thousand physical qubits per logical qubit and thus machines orders of magnitude larger than today's.

What actually works right now

  • Learning and teaching. Everything in this book runs. This is not a consolation prize; the skills are real and transferable.
  • Small algorithm demonstrations. Grover on 3–4 qubits, Deutsch–Jozsa, Bernstein–Vazirani, teleportation, BB84, small QFTs. These give clean, correct, interpretable results on real hardware today.
  • Variational chemistry on small molecules. H₂, LiH, BeH₂ with active-space reduction. Results within chemical accuracy are achievable with mitigation. This is the strongest near-term application, and it is where this book's project lands.
  • Hardware benchmarking and characterization. A large and genuinely productive research area.
  • Random circuit sampling. Demonstrated at scales that are hard to simulate classically. Its practical usefulness is essentially nil, which the researchers involved have generally been clear about.

What does not work right now

  • Breaking RSA. Not close. Chapter 23 gives the resource estimate: millions of physical qubits and hours to days of runtime, against today's machines with about a thousand noisy qubits. Estimates have been improving — the required resources have come down substantially over the past decade as algorithms and error-correction schemes improved — but the gap remains many orders of magnitude.
  • Beating classical optimizers. QAOA does not currently beat classical heuristics on any problem of practical size. Chapter 37 shows the comparison honestly.
  • Useful machine learning. Quantum models do not currently outperform classical models on natural datasets. Chapters 33 and 34 show the comparison and are blunt about it.
  • Any commercial application with a demonstrated, reproducible quantum advantage. As of this writing there is none. There are pilot projects, proof-of-concept papers, and press releases; the gap between those and a reproducible advantage is where most of the field's credibility problem lives.

The size of the gap, in numbers measured later in this book

Those four bullets are the qualitative version. Each one is a measurement somewhere in the back half of this book, and the measurements are more useful than the adjectives — they make this section falsifiable rather than merely cautious. Here is what the comparisons actually returned:

   claim                        chapter   what was measured
   ------------------------------------------------------------------------------
   quantum classifiers          Ch. 33    data reuploading 0.8343 vs kNN 0.8970
   quantum kernels              Ch. 34    kernel SVM 0.8313 +/- 0.0381 against
                                          SVC(rbf) 0.8889, over ten splits
   hybrid architectures         Ch. 35    quantum-data model 0.6429 vs
                                          SVC(rbf) 0.7857
   combinatorial optimization   Ch. 37    ten MaxCut instances: QAOA 0 wins,
                                          Goemans-Williamson 6, 4 ties
   the whole book               Ch. 40    six head-to-head comparisons against
                                          tuned classical baselines: zero
                                          quantum wins, one exact tie

★★ Zero wins in six head-to-head comparisons is this book's single most important result, and it is not the result the outline predicted. Chapter 40 §40.3 lays out all six.

Two things that number does not mean. It does not mean the techniques are broken: every one of them runs, converges, and produces the physics it is supposed to produce. And it does not mean the comparisons were tilted the other way — Chapter 34 states explicitly that a more thoroughly tuned SVC(rbf) would likely score above 0.8889, not below. That same chapter also warns against the comparison that looks easier: kNN's 0.8970 belongs to a different model class than a kernel SVM, so quoting it as the quantum kernel's opponent silently swaps the question. "Compared to what?" has to be settled before "by how much?" (Chapter 21 §21.7.)

Optimization loses on a dimension that is not accuracy at all. Chapter 37 clocks Goemans–Williamson at 5.9 ms against QAOA's 5.2 s on the same instances, and — more damaging — Goemans–Williamson returns a certificate: its semidefinite bound proves its own answer is within a factor 0.9975 of optimal, without anyone knowing the optimum. QAOA returns a number and no way to check it. "What does it produce, not just how does it score?" is a question no hardware improvement answers, because the certificate gap is a property of the method.

The chemistry gap is the largest and the easiest to state. Chapter 36 prices one VQE energy evaluation at the classical crossover — 50 orbitals, where exact classical diagonalization genuinely gives out — at $1.91 \times 10^{20}$ shots. At the 10,000 shots per second that chapter assumes, which is the same 100 µs per shot this chapter's own shot-budget model uses, that is

$$1.91\times10^{20}\ \text{shots} \times 10^{-4}\ \text{s} \;=\; 1.91\times10^{16}\ \text{s} \;=\; 6.06\times10^{8}\ \text{QPU-years}$$

for one point on one potential energy surface. Chapter 36 then strips out every negotiable factor it can find — Pauli grouping, better ansätze, classical shadows — and still lands at 1.94 QPU-years for that single evaluation. The deficit is not a few orders of magnitude of engineering.

Nor does error correction close it for free. Chapter 15 runs the Azure Quantum Resource Estimator on a circuit needing 450 physical qubits with zero T gates and 2,882 with one — a 6.4× jump for a single gate, because that one gate forces a magic-state factory into the layout. Chapter 15 is then careful about what the 6.4× is a statement about: rerun the same estimate at a physical error rate of $10^{-4}$ instead of $10^{-3}$ and the first T gate costs 18 extra qubits rather than 2,432 — a 1.11× jump. The cliff does not vanish; it moves to the fifth T gate. The number measures the gap between hardware quality and algorithmic demand, not a constant of nature. That is the shape of nearly every discouraging number in this book, and it is why none of them is a proof that the field fails.

💰 Cost and Queue — What that time costs in dollars, today.

Chapter 39 §39.5 prices a single VQE run — the LiH (2e,2o) job from Chapter 36, 18,456,984 shots, 31.2 seconds of actual processor time — against three real commercial billing structures:

text per-minute, superconducting $50 per-shot, superconducting $7,432 (149x) per-shot, trapped ion $185,542 (3,718x)

A factor of 3,718 between the cheapest and the dearest way to buy the identical computation. Today the price of a quantum calculation is a billing-model question at least as much as a physics question, and a cost estimate that does not name its billing model is not an estimate.

Chapter 39 §39.3 also measures where the wall-clock time goes. A job that occupies the processor for 6.92 ms and then waits in a five-minute queue achieves a hardware utilization of $2.31 \times 10^{-5}$ — wall clock is 43,340× device time. Batching circuits and running inside a session is consequently the largest single speedup available to you, it costs nothing, and it is worth knowing about long before you need it.

🔬 Honest Assessment — How to read a quantum claim.

When you see a quantum computing announcement, ask these five questions in order.

  1. What exactly was computed, and was the answer already known? Most demonstrations solve problems whose answers were computed classically first, in order to verify. That is good science and it is not an advantage claim.
  2. What is the classical baseline, and who ran it? If the comparison is against a naive classical algorithm rather than the best known one, the comparison is worthless. Several high-profile "advantage" claims were subsequently matched or beaten by improved classical methods within months.
  3. How many qubits, and were they error-corrected? "1,000 qubits" without error correction is a different object from "10 logical qubits."
  4. Was the result reproducible by someone outside the company? Frequently not, and frequently not possible, since the hardware is unique.
  5. Is the claim about today or about a roadmap? Roadmaps are legitimate and useful. A roadmap reported as a capability is not.

Applying these five will make you the most useful person in most rooms where quantum computing comes up. It will also occasionally make you unpopular. That trade is worth making.

Why learn this now, then?

Two honest reasons.

The skills are durable and the ramp is long. Quantum programming takes months to internalize — not because the APIs are hard but because the mental model is genuinely foreign. The transpilation intuition, the statistical discipline, the debugging techniques: none of that transfers from classical programming and all of it will still be relevant when the hardware improves, because it is about the computational model rather than about any specific device.

The field is small and the on-ramps are open. Qiskit is open source and accepts contributions. IBM hardware is free. The papers are on arXiv. There is no gatekeeping infrastructure of the kind that surrounds most specialized fields, and someone who does good work in public gets noticed quickly. Chapter 40 makes this case in detail with the actual hiring picture.

What this book will not tell you is that quantum computing will definitely be transformative by a particular year. Nobody knows that. What is knowable is that the software layer is being defined right now, by a small number of people, in the open.

1.6 How This Book Works

A brief orientation, because the structure is deliberate.

Code first. Every concept arrives as code, then gets explained. This inverts the usual textbook order and it is the right choice here, because the mathematics of quantum computing is genuinely difficult and the code is genuinely not. You can build correct intuition from working programs and backfill the theory. The reverse — a full theory course followed by programming — is how most people bounce off this subject.

Hardware early and often. You run on a real quantum processor in Chapter 2, before you have learned what a Bloch sphere is. This is on purpose. Nothing teaches you what noise is like seeing your own Bell state come back imperfect.

Five frameworks, one at a time. Qiskit is the spine. The others get dedicated chapters in Part III and appear throughout as 🔀 In Another Framework callouts, so your fluency builds a paragraph at a time rather than in one lump.

Honesty as a feature. The 🔬 Honest Assessment callouts are load-bearing. Every time this book covers a technique that does not currently beat a classical alternative, it says so and shows the comparison.

Where the numbers in this book come from

Every result in these forty chapters was produced by running code. Where a number appears in a text output block in this book, a script printed it, and that script is in the chapter's code/ directory — not estimated, not lifted from a vendor's specification sheet, not carried over from a paper's abstract. Chapter 40 totals the effort: 264 Python files, 41,427 lines, and 503 checkpoint tests, every example executed.

The distinction that word result is doing is deliberate, and §1.5 above is the place to see it. The qubit counts in that section — Eagle's 127, Osprey's 433, Condor's 1,121, Willow's 105 — are citations, not measurements. Nobody here counted them. They are reported as announcements because that is what they are, and a reader is entitled to know which numbers in a book carry the author's own arithmetic behind them and which carry someone else's press release. When those two get blended, the second kind quietly inherits the credibility of the first.

The environment is pinned — in Appendix C and at the top of every script — because "it worked on my machine" is not reproducibility in a field whose APIs move this fast:

   qiskit 2.5.1            qiskit-aer 0.17.2      qiskit-ibm-runtime 0.48.0
   pennylane 0.45.1        cirq 1.7.0             scikit-learn 1.9.0
   networkx 3.6.1          cvxpy 1.9.2            cryptography 50.0.0

That policy has a cost, and the cost is the interesting part. When you commit to measuring everything, some of the measurements come back disagreeing with what you had already written. Seven times in this book they did, and in all seven the same thing had gone wrong: a conclusion drawn from a sample too small to carry it. Those seven are not quietly patched. They are printed — the wrong number, the right number, and the reason — because the failure mode is more useful to you than the corrected value.

The clearest one is in Chapter 27 §27.5, and it is worth knowing now, because it is the mistake you are most likely to make yourself. That chapter needed the rate at which a correct quantum test falsely fails. It ran the test 200 times, saw 2 failures, and reported 1.0%. Re-run at 2,000 runs, the rate was 0.150%; at 3,000 runs, 0.100%. The first estimate was nearly seven times too high, and it was too high for a reason that generalizes: at 200 runs, the standard error on a rate near 0.15% is roughly 0.7% — larger than the rate itself — so 0, 1, 2, or 3 failures are all ordinary outcomes of the same underlying truth.

📊 What the Numbers Say — Why the wrong number is the one that stops the search.

Look at the shape of that error. The 2-in-200 measurement did not fail because the code was buggy or the statistics exotic. It failed because 200 runs was cheap, the answer it gave was plausible, and a plausible answer ends an investigation.

This is the most reliable failure mode in empirical work, and it has a name in this book: the easy number is almost always the flattering one, because it stops the search. It is why Chapter 27 §27.5 insists on the rule of three — 0 failures in $N$ runs bounds the rate at about $3/N$, not at zero — and why the same chapter reports the shot noise of a correct GHZ(3) circuit as a spread rather than a value:

text shots mean TVD max over 40 runs 1/sqrt(N) 1,000 0.01313 0.03700 0.03162

The mean and the worst case differ by a factor of 2.8. A test tolerance chosen from a single run of a correct circuit will be about a third of what it needs to be, and the suite will then flake forever on code that is right. Same lesson as the false-failure rate, arriving from the opposite direction: a result from one or two samples is a draw from a distribution.

You will meet that sentence six more times.

Twelve callout devices, described in the front matter and used consistently across all forty chapters. Learn the icons; they let you skim for what you need.

Seven files per chapter — the chapter, exercises, a quiz, two case studies, a one-page reference, and tiered further reading — plus a code/ directory with everything runnable.

1.7 The Project: vqelab

Starting in Chapter 2 and finishing in Chapter 36, you build one program across the whole book.

The goal: compute the ground-state energy of the hydrogen molecule, H₂, on a real quantum processor, using a Variational Quantum Eigensolver.

The success criterion, stated now so it is testable: the computed energy must be within 1.6 millihartree — chemical accuracy, about 1 kcal/mol — of the exact value for H₂ in a minimal STO-3G basis at its equilibrium bond length of 0.735 Å, which is approximately −1.137 Hartree.

That is a real scientific claim with a real pass/fail threshold, and it is achievable on today's free hardware with the mitigation techniques in Chapter 13. It is also, not coincidentally, one of the few things a current quantum computer does that is genuinely interesting.

The architecture you will build:

vqelab/
    circuits.py       parameterized ansatz circuits          (Ch. 3, 4, 8, 28)
    hamiltonian.py    Pauli-string Hamiltonians              (Ch. 19, 36)
    backends.py       one interface over sim + 5 platforms   (Ch. 2, 7, 10, 12, 14, 16, 17, 29, 39)
    measure.py        counts → expectation values + errors   (Ch. 5, 9)
    optimize.py       the classical optimization loop        (Ch. 24)
    mitigate.py       readout mitigation, ZNE                (Ch. 13)
    bench.py          ansatz benchmarking                    (Ch. 30)
    qml/              the ansatz as a trainable model        (Ch. 32-35)
    tests/            statistical + property + statevector   (Ch. 27)

Every chapter adds exactly one piece, marked with a 🧱 Project Checkpoint callout and implemented in code/project-checkpoint.py. The checkpoints are cumulative — skip several in a row and the next one will not run.

🧱 Project Checkpoint — Chapter 1: write down the claim.

Your first checkpoint involves no quantum code at all. Create the project directory and a README.md that states, in your own words:

  1. The goal. "Compute the ground-state energy of H₂ using VQE on quantum hardware."
  2. The success criterion. "Within 1.6 mHa of −1.137 Ha (STO-3G, 0.735 Å)."
  3. The falsification condition. "If the mitigated hardware result is outside that window, the project has failed, and I will report the gap rather than adjust the criterion."

That third item is not ceremony. In a field where output is probabilistic and every result needs interpretation, the temptation to retroactively decide what counts as success is enormous and it is how a great deal of unreliable work gets published. Writing the threshold down before you have any data is the cheapest scientific discipline available to you.

The starter file is in this chapter's code/project-checkpoint.py.

1.8 Summary

A quantum program is a circuit: a fixed sequence of gates on a fixed number of qubits, ending in measurements. It compiles — heavily — before it runs, and what runs is not what you wrote. It returns a distribution over bitstrings, not a value, and extracting an answer from that distribution is a statistical problem you own.

There are five major frameworks because the field has not converged, and it has not converged because the hardware has not converged. Qiskit bets on circuits and compilation and gives you free hardware. Cirq bets that scheduling and physical placement belong in the program. PennyLane bets that circuits are differentiable functions. Q# bets that quantum programming needs a real language. Braket bets on hardware portability. OpenQASM is the assembly language they all pass through, and the interchange format between them.

The stack runs from application through algorithm, circuit, intermediate representation, transpiler, pulse, and control electronics to the processor itself. Unlike a classical compiler, the transpiler's choices determine whether you get an answer at all — because every added gate adds error and every added nanosecond adds decoherence.

Four properties make this different from all your prior programming experience. Output is probabilistic, so testing becomes statistical and precision costs shots quadratically. You cannot copy a qubit, so there is no checkpointing and no majority-vote error correction — but there is quantum key distribution. Measurement destroys the state, so print is unavailable and debugging becomes indirect. Entanglement is a resource, which is where the exponential power comes from and where most of the bugs come from too.

Today's hardware is NISQ: hundreds to low thousands of noisy qubits, gate errors around a few parts per thousand, coherence budgets of hundreds to a few thousand operations. Small algorithms, small-molecule chemistry, benchmarking, and learning all work. Breaking RSA, beating classical optimizers, and useful quantum machine learning do not. When you read a quantum claim, ask what was computed, what the classical baseline was, whether the qubits were error-corrected, whether anyone outside reproduced it, and whether the claim is about today or a roadmap.

Learn Qiskit first, then one other framework chosen by what you do. Learn to read all five.

The project starts now: a VQE for H₂, target −1.137 Ha, tolerance 1.6 mHa, criterion written down before any data exists.


Next: Chapter 2 — install everything, get an IBM Quantum account, and run your first program on a real quantum processor. You will have results from physical hardware within the hour, and the first one will be slightly wrong in a way that is about to teach you a great deal.