Cirq Fundamentals

Lesson 6 of 8

Building a Quantum Random Number Generator

The same idea from the Qiskit course, superposition plus measurement equals genuine, physically unpredictable randomness, works identically in Cirq, just with different method names.

The Cirq version

import cirq

def quantum_random_bits(n_bits):
    qubits = cirq.LineQubit.range(n_bits)
    circuit = cirq.Circuit()
    circuit.append(cirq.H(q) for q in qubits)               # every qubit into superposition
    circuit.append(cirq.measure(*qubits, key='result'))

    simulator = cirq.Simulator()
    result = simulator.run(circuit, repetitions=1)           # one measurement, one random outcome
    value = result.measurements['result'][0]                 # a length-n_bits array of 0s and 1s
    bitstring = ''.join(str(bit) for bit in value)
    return int(bitstring, 2)

print(quantum_random_bits(8))  # a random integer from 0 to 255
print(quantum_random_bits(8))  # a different one, genuinely unpredictable
  • circuit.append(cirq.H(q) for q in qubits) appends an H operation for every qubit in one line, a generator expression works here exactly like the list-of-operations pattern from earlier lessons.
  • cirq.measure(*qubits, key='result') measures all n_bits qubits at once under a single key, unpacked with *qubits since measure takes qubits as separate positional arguments.
  • result.measurements['result'] is a 2D array (one row per repetition), [0] grabs the single repetition's row, an array of individual 0/1 bit values, which then gets joined into a bitstring and parsed as base-2, exactly like the Qiskit version.

Why the physics matters more than the syntax

Notice this lesson is almost a line-by-line translation of the Qiskit RNG function, that's the point: the physical source of randomness (measuring a qubit in superposition) is identical regardless of which SDK expresses it. What differs is purely how each library's API is shaped, shots vs repetitions, bitstrings vs integer histograms, a classical register vs measurement keys.

TIP

If you've completed both this course and the Qiskit one, try porting a circuit from one SDK to the other from memory, it's one of the best ways to confirm you understand the underlying quantum concepts rather than just one library's syntax.

📝 Quantum RNG Quiz

Passing score: 70%
  1. 1.Why does quantum_random_bits use cirq.measure(*qubits, key='result') instead of measuring each qubit separately?

  2. 2.The physical source of randomness (measuring superposition) is the same in Cirq and Qiskit, only the API syntax differs.

  3. 3.cirq.measure(*qubits, key='result') unpacks the qubits list using Python's ____ operator.