Skip to content

Measurement ​

Measurement is how we extract classical information from quantum states. When you measure a qubit, its superposition collapses to either 0 or 1.

The measure() Function ​

Use measure(qubit) to collapse a qubit and get a classical bit:

Measurement Collapses State ​

Before measurement, a qubit in superposition has probabilities for both outcomes. Measurement forces it into a definite state:

|0>                    -> always measures 0
|1>                    -> always measures 1
(|0> + |1>)/sqrt(2)    -> measures 0 or 1 with 50% probability each

After measurement, the qubit is consumed - it cannot be used again.

Running Multiple Shots ​

Quantum algorithms are probabilistic. To see the distribution of outcomes, run multiple shots:

The shots Parameter ​

The quantum_simulator(shots = N) handler runs your quantum function N times:

kettle
fn main() -> Unit using quantum_simulator(shots = 100), file_io
  results = my_quantum_fn()  -- returns List[T] with 100 elements
end fn

Without shots, you get a single execution:

The counts() Function ​

Use counts() to get a frequency distribution:

Mid-Circuit Measurement ​

You can measure qubits in the middle of a circuit and use the results to control later operations:

The cgate(condition, gate) applies a gate only when the classical bit is 1. This enables classical feedback within quantum circuits.

Teleportation Example ​

Quantum teleportation uses mid-circuit measurement and classical feedback:

This demonstrates:

  1. Creating an entangled Bell pair
  2. Bell measurement (mid-circuit)
  3. Classical corrections based on measurement outcomes

Expectation Values ​

Sometimes you need to know the expected measurement outcome without actually collapsing the qubit. The expect_z function computes the Pauli-Z expectation value ⟨ψ|Z|ψ⟩:

How It Works ​

The expect_z function returns an Expectation record with two fields:

  • exp.value: The expectation value (weighted average of measurement outcomes)
  • exp.std_error: The standard error of the estimate

The expectation value tells you:

  • +1 for |0⟩ (would always measure 0)
  • -1 for |1⟩ (would always measure 1)
  • 0 for equal superposition (50/50 chance)
  • cos(θ) after ry(θ) rotation

Simulation Modes ​

By default, expect_z uses statistical sampling. For debugging with exact values, use quantum_simulator(exact = True). See Backends for details.

Non-Destructive ​

Unlike measure, expect_z does not collapse the qubit:

kettle
(exp, q) = expect_z(q)  -- Returns (Expectation, Qubit) tuple
-- Access the value and error
print(exp.value)
print(exp.std_error)
-- q can still be used!
q <- hadamard
measure(q)

This is essential for variational algorithms (VQE, QAOA) where you compute energies many times during optimization.

Use Cases ​

  • VQE: Compute molecular ground state energies
  • QAOA: Evaluate cost function for optimization problems
  • Quantum machine learning: Gradient computation for training