Skip to Content
Quantum Circuits

Quantum Circuits

A quantum circuit is an ordered series of quantum gates acting on a collection of qubits. By selecting appropriate gates we can create superposition, entangle qubits and ultimately perform a computation. The final measurement step converts the quantum state into classical information.

The unitary portion of a circuit corresponds to an operator formed by multiplying the matrices of its gates. If U1U_1 acts first and U2U_2 acts second, the overall transformation is U2U1U_2U_1. Matrix products are written in the reverse of the temporal order because each new gate multiplies the state from the left. For an nn‑qubit register this unitary has dimension 2n×2n2^n\times2^n. Measurements, resets and noisy channels require the more general formalism of quantum operations rather than a single unitary matrix.

Quantum circuits can be visualised as diagrams where qubits are represented by horizontal lines and gates are applied at discrete time steps. Gates acting on disjoint qubits in the same time step combine with a tensor product: a gate UU on qubit 0 while qubit 1 is left alone is the two‑qubit operator UIU\otimes I.

Everything on this page can be reproduced in the Quantum Simulator . Add or remove operations in the builder, select Run, and inspect the resulting probabilities, counts and reduced-state Bloch spheres.

Designing a Circuit

A quantum circuit consists of three main steps:

  1. Choose the qubits. Decide how many qubits are required to represent the problem.
  2. Apply gates. Arrange single‑ and multi‑qubit gates to implement the desired transformation.
  3. Measure. Read out the qubits to obtain classical results.

When multiple qubits interact, the number of complex amplitudes needed to describe a general pure state grows exponentially: nn qubits require 2n2^n of them. That large state space can make quantum systems hard to simulate classically, though the dimension alone does not guarantee a computational advantage. Algorithms must exploit structure such as interference in a way that yields useful measurement statistics.

Measurements are described by projectors onto the computational basis. Measuring qubit kk yields outcome b{0,1}b\in\{0,1\} with probability Πb(k)ψ2\lVert \Pi_b^{(k)}|\psi\rangle \rVert^2, the sum of the squared amplitudes of all basis states in which qubit kk equals bb; the state then collapses to the renormalised Πb(k)ψ/Πb(k)ψ\Pi_b^{(k)}|\psi\rangle / \lVert \Pi_b^{(k)}|\psi\rangle \rVert. If that qubit is entangled with others, the collapse updates their amplitudes too, which is exactly the correlation the Bell state below exhibits.

Using the Quantum Simulator

Open the Quantum Simulator  and choose Circuit Builder. The builder separates circuit definition from execution: configure the register and add gates first, then select Run to calculate results. This distinction is useful because changing a gate does not silently replace the displayed output; the status at the top tells you whether results are ready or the edited circuit is awaiting another run.

Know the builder’s scope

The current gate palette contains H, X, Y, Z, RX, RY, RZ, CNOT, Swap, Toffoli, controlled phase, Oracle and Diffusion. This is enough for the small circuits in these tutorials, but the builder is not a general hardware or noise-modeling environment.

TaskQSim supportPractical implication
Prepare a computational-basis inputBuilt in through integer entry and bit togglesCreate a superposition by adding gates after initialization
Apply the listed ideal unitary gatesBuilt inDecompose other operations into the available gates
Use a marked-state phase oracleBuilt in through OracleSelect its target register and enter the marked local integer
Apply Grover diffusionBuilt in through DiffusionUse it on the same search-register targets as the Oracle
Measure for classical feed-forwardBuilt in through a conditional operationThe condition measurement creates branches and cannot share a qubit with that operation’s targets
Add an unconditional terminal measurement gateNot a separate circuit operationSelecting Run already reports computational-basis output probabilities and sampled counts
Enter an arbitrary state vector or density matrixNot available in the builderPrepare reachable pure states with gates; mixtures arise from measurement branches
Configure depolarising, damping or dephasing noiseNot available in the builderThe noise channels on the measurement page are theory, not controls exposed by QSim
Simulate gate durations, connectivity or calibration errorsNot availableDo not interpret a QSim circuit as a hardware performance estimate
Define an arbitrary custom matrixNot available through the interfaceDecompose it into supported rotations and controlled gates, or use a specialized simulator

Knowing these boundaries saves time. For example, increasing Shots reduces sampling uncertainty, but it does not add physical noise, improve a gate model or turn an ideal circuit into a fault-tolerance simulation.

A fast, reliable builder workflow

Use the controls in this order to avoid most indexing and stale-result mistakes:

  1. Set Number of Qubits first. Reducing the register later removes operations that refer to qubits outside the new range. Qubits are numbered from q0, and the builder supports registers from 1 through 30 qubits. Large state spaces may still be expensive even though the interface accepts them.
  2. Choose the Initial basis state. Enter its non-negative integer value or use the per-qubit toggles. The displayed ket is the authoritative check that the bit pattern is the one you intended. For example, on three qubits, integer 5 is displayed as |101⟩.
  3. Enter target qubits before selecting a gate. The gate buttons become available only when the target count is valid. Use one index for H, X, Y, Z, RX, RY or RZ; two distinct indices for CNOT, Swap or controlled phase; and three distinct indices for Toffoli.
  4. Treat target order as part of the operation. For CNOT, the first listed qubit is the control and the second is the target. For Toffoli, the first two are controls and the third is the target. Swap and the standard controlled-phase operation are symmetric, but entering their indices consistently still makes circuits easier to review.
  5. Set parameters before choosing Add Gate. Rotation and controlled-phase angles are entered in radians. The Oracle control is an integer whose binary representation identifies the marked basis state within the selected target qubits.
  6. Inspect the circuit diagram, then run. Hovering a column identifies the operation, including its targets, parameters and any condition. Remove an individual column when only one step is wrong; Remove last gate is faster while building forward; Reset circuit clears the whole operation list.

The builder also includes Bell (2), GHZ (3), All-H and Grover (2) presets. Begin with a preset when learning a pattern, run it once to establish the expected output, and then change one gate or parameter at a time. This controlled comparison is more informative than assembling a long unfamiliar circuit before the first run.

Qubit order and integer encoding

QSim uses little-endian qubit indices: q0 contributes the least significant bit to the basis-state integer, while the displayed ket writes the most significant qubit on the left. If the toggle values are b0,b1,,bn1b_0,b_1,\ldots,b_{n-1}, the integer field is

x=j=0n1bj2j,x = \sum_{j=0}^{n-1} b_j 2^j,

and the displayed ket is bn1b1b0|b_{n-1}\cdots b_1b_0\rangle. Thus, on three qubits, toggling q0 and q2 gives integer 5 and displays |101⟩; toggling only q0 gives integer 1 and displays |001⟩.

This ordering also applies inside a selected multi-qubit operation. For target list 2,0, the first selected qubit, q2, is local bit 0 of the gate matrix and the second, q0, is local bit 1. For CNOT this first target is the control by QSim’s gate convention. Keep target lists in ascending order when an operation is symmetric, and write the intended control first when it is not.

Reading results efficiently

After selecting Run, use the three result views for different questions:

  • Measurement Results lists computational-basis probabilities and shot counts. Probabilities describe the simulated distribution; counts are samples governed by the Shots setting and therefore fluctuate. If a probability is near pp, the typical sampling uncertainty of its observed frequency is approximately p(1p)/N\sqrt{p(1-p)/N} for NN shots.
  • Bloch Sphere Visualization shows each qubit’s reduced state, not the complete multi-qubit state. The radius rr is 1 for a pure reduced state and less than 1 for a mixed reduced state. A Bell pair puts both local vectors at the origin even though the joint state is pure. Use probabilities or correlations as well as Bloch spheres when studying entanglement.
  • Export CSV records every basis state rather than only the rows currently visible in the table. For a circuit without measurement branches, the CSV can include complex amplitudes. When mid-circuit measurement produces a mixture, there is no single amplitude vector for that mixture, so the export contains probabilities instead.

Keep the results table collapsed to its first rows while iterating on a large register. Choose Show all only when the complete 2n2^n table is genuinely needed. Likewise, use the Bloch controls to hide, collapse or limit rendered spheres. These controls reduce browser rendering work, but they do not reduce the cost of simulating the quantum state itself.

Shots, exact branches and conditional gates

The default shot count is 1024 and can be changed up to 1,000,000. More shots reduce sampling noise but increase runtime. A useful workflow is to debug with 100 to 1,000 shots, then increase the count only for the final comparison. For an event near probability 1/21/2, about 10,000 shots gives a sample-proportion standard deviation of roughly 0.0050.005.

The Conditional (measure qubit equals value) option models measurement followed by classical feed-forward. Choose a condition qubit and the value 0 or 1, then add a gate on different target qubits. The condition qubit cannot also be a target of that operation. This feature is useful for teleportation corrections and other adaptive circuits, but it changes how results must be interpreted:

  • With a manageable number of branches, the simulator enumerates them exactly and averages probabilities and reduced Bloch vectors using branch probabilities.
  • When there are too many branches to enumerate, it estimates the mixture from sampled runs. In that mode, increasing Shots makes the estimate steadier.
  • A conditional operation is not coherent quantum control. It first obtains a classical measurement result and then decides whether to apply the gate. Use CNOT or another controlled unitary when no measurement is intended.

Save, share and reproduce

Choose the persistence option according to the task:

  • Save and Load use storage in the current browser. They are convenient for a circuit you will revisit on the same device, but they are not a portable backup.
  • Export JSON downloads the register size, initial basis state and ordered operations. Import JSON reconstructs that circuit. Use this pair for reproducible exercises or version-controlled examples.
  • Share URL copies a link containing the circuit definition. It is the quickest way to send a runnable example, although very large circuits produce longer URLs.
  • Export PNG captures the circuit diagram for a report. Use JSON or a share URL as well when the recipient needs to rerun or edit the circuit, because a PNG is only a picture.

Before sharing, load the JSON or open the copied URL in a fresh browser tab and run it again. Confirm the displayed initial ket, gate ordering and expected high-probability outcomes. This short reproducibility check catches reversed CNOT targets and forgotten parameter changes.

What an exported circuit contains

An exported JSON file is small enough to inspect directly. A Bell preparation has the following structure:

{ "numQubits": 2, "initialBasisState": 0, "operations": [ { "gateName": "Hadamard", "qubits": [0] }, { "gateName": "CNOT", "qubits": [0, 1] } ] }

Parameterized operations add a numeric params array. A classically conditioned operation also has a condition object such as { "qubit": 0, "value": 1 }. Prefer exporting from the interface over writing JSON manually: import validates the outer structure, but an unsupported gate name or invalid arity will still fail when the circuit is reconstructed.

JSON stores the circuit, not a particular random sample of counts. To reproduce sampled results, record the shot count separately. CSV stores the most recently calculated state data, while PNG stores only the diagram. These formats answer different questions and are not interchangeable.

Performance and troubleshooting

The register limit is not a promise that every 30-qubit circuit will run comfortably. QSim stores populated amplitudes sparsely, so memory grows with the number mm of nonzero basis amplitudes rather than always allocating all 2n2^n entries. Gate work also grows with mm and with the gate’s arity. A generic 30-qubit state can still have 2302^{30} nonzero amplitudes. Start with the smallest instance that tests the idea, hide excess Bloch spheres, and scale one qubit at a time while watching browser responsiveness.

Use this checklist when an output is surprising:

SymptomLikely causeEfficient check
A gate button is disabledWrong number of targets, repeated index or out-of-range indexRe-enter the comma-separated target list before selecting the gate
CNOT changes the wrong lineControl and target were reversedHover its column; the first target should have the control dot
Results do not match the diagramThe circuit changed after the last runCheck for Awaiting run, then select Run again
Counts change between identical runsShot sampling is randomCompare exact probabilities, or increase Shots
Bloch radius is below 1The qubit is entangled or in a branch-averaged mixtureInspect joint probabilities and the measurement-branch notice
CSV export is disabledNo current result existsRun the circuit before exporting
Imported circuit failsJSON shape, gate name, parameter or target list is invalidExport a minimal working circuit and compare its schema
A large page feels slowToo many basis rows, Bloch canvases or populated amplitudesShow first rows, hide Bloch spheres and reduce the register

A reproducible experiment template

For exercises, bug reports or comparisons, record the following information in this order:

  1. QSim URL and the date used, because a hosted application can evolve independently of these tutorials.
  2. Exported circuit JSON, which fixes register size, initial basis integer and ordered operations.
  3. The displayed ket, since it makes endianness mistakes visible immediately.
  4. Expected exact probabilities or other invariants before looking at sampled counts.
  5. Shot count and observed counts when sampling matters.
  6. Whether the branch notice says results were enumerated exactly or estimated from sampled runs.
  7. Any display-only settings, such as angle units or hidden Bloch spheres, that affect a screenshot but not the simulated circuit.

Change only one circuit feature between trials. If changing a rotation angle, keep targets and initial state fixed; if testing CNOT direction, keep the input fixed; if studying shot noise, keep the circuit fixed. This one-variable-at-a-time method turns the builder into a controlled experiment rather than a trial-and-error drawing tool.

Example: Creating a Bell State

The following sequence prepares two qubits in an entangled Bell state. Try these steps in the simulator to see the states evolve:

  1. Start with both qubits in |0⟩.
  2. Apply a Hadamard gate to the first qubit.
  3. Apply a controlled‑NOT with the first qubit as control and the second as target.

Tracking the state through each step:

00    HI    12(00+10)    CNOT    12(00+11).|00\rangle \;\xrightarrow{\;H\otimes I\;}\; \tfrac{1}{\sqrt{2}}(|00\rangle + |10\rangle) \;\xrightarrow{\;\mathrm{CNOT}\;}\; \tfrac{1}{\sqrt{2}}(|00\rangle + |11\rangle).

The CNOT leaves the 00|00\rangle branch alone and flips the second qubit in the 10|10\rangle branch, giving

Φ+=12(00+11).|\Phi^+\rangle = \tfrac{1}{\sqrt{2}}(|00\rangle + |11\rangle).

As a whole circuit this is the unitary CNOT(HI)\mathrm{CNOT}\,(H\otimes I), with HIH\otimes I written on the right because it acts first.

This circuit is a building block for many protocols and illustrates how simple gate sequences yield entanglement. Measuring either qubit in the computational basis produces a random bit with probability 1/21/2 for each outcome, and subsequent computational-basis measurement of the other qubit always gives the same result.

Last updated on