ProductBlogAlgorithmsAboutSign inSign up

Learning Tutorial

Hamiltonian Simulation: Exact Evolution and Trotter Steps

Simulate a one-qubit Hamiltonian with noncommuting terms and compare a short product formula with exact time evolution.

1 qubit · 6 step counts · 4,096 samples per circuit

How does replacing simultaneous evolution by alternating rotations change a measurable probability?

Define the teaching problem

Use H = (X + Z)/√2, initial state |0⟩, ℏ = 1 and dimensionless time t = π/2. X and Z do not commute, so applying their evolutions sequentially is generally an approximation.

Because H² = I, the exact unitary is cos(t) I − i sin(t) H, and exact P(1) = sin²(t)/2. This gives a transparent independent reference for a tiny teaching system.

Follow the workflow

  1. For n steps, apply Rx(√2 t/n), then Rz(√2 t/n), n times. In matrix order this is [exp(−it Z/(√2 n)) exp(−it X/(√2 n))]ⁿ; the rightmost factor acts first.
  2. Compute the ideal product-formula state for n = 1, 2, 4, 8, 16 and 32. Compare both its complex state and its Z-measurement probability with exact evolution.
  3. Sample 4,096 ideal shots for each approximate circuit. Compare samples with that circuit’s own ideal probability, then compare that ideal probability with the exact evolution. These are two different errors.

Compare with the expected result

Scroll the table horizontally to see every column.

Ideal mathematical references, not hardware measurements
Trotter stepsIdeal product-formula P(1)Exact P(1)
10.8028500.500000
20.5796640.500000
40.5194650.500000
80.5048310.500000
160.5012060.500000
320.5003010.500000

This is a first-order Lie–Trotter formula, with generic fixed-time operator error O(1/n). This particular population converges faster; the table does not make the method second order or establish monotone convergence for arbitrary systems.

At 4,096 shots, sampling fluctuations near probability 1/2 have a standard error of about 0.0078. They can obscure the small approximation error at larger n. A sampled histogram need not improve monotonically.

Reversing the rotations gives the same Z probabilities in this setup. A histogram alone cannot verify ordering or phases; the checks compare full complex states against independent matrix evolution. The script’s state infidelity is an ideal mathematical diagnostic, not a quantity inferred from the sampled histogram.

Run the complete tutorial locally

Download the complete Python tutorial, then open a terminal in the folder containing hamiltonian-simulation.py.

Use Python 3.10 or later and NumPy 2.x. From that folder, create a virtual environment, install NumPy and run the script. The code uses explicit small statevectors and local pseudorandom sampling. It requires no Marqov account, credentials or external service.

python3 -m venv .venv
source .venv/bin/activate
python -m pip install 'numpy>=2,<3'
python hamiltonian-simulation.py
Inspect the complete Python source
"""Learning: noncommuting time evolution H=(X+Z)/sqrt(2), not a replication.
Run: python hamiltonian-simulation.py (NumPy required). No network/jobs.
Units hbar=1; dimensionless time; initial |0>. Chronological Rx then Rz.
Background: Lloyd (1996), doi:10.1126/science.273.5278.1073.
"""
import json
import math
import numpy as np

I = np.eye(2, dtype=complex)
X = np.array([[0, 1], [1, 0]], dtype=complex)
Z = np.diag([1, -1]).astype(complex)
H = (X + Z) / math.sqrt(2)
INITIAL = np.array([1, 0], dtype=complex)


def trotter_state(steps, time=math.pi / 2):
    if type(steps) is not int or steps <= 0:
        raise ValueError("steps must be a positive integer")
    a = time / (math.sqrt(2) * steps)
    ux = math.cos(a) * I - 1j * math.sin(a) * X
    uz = math.cos(a) * I - 1j * math.sin(a) * Z
    return np.linalg.matrix_power(uz @ ux, steps) @ INITIAL


def exact_state(time=math.pi / 2):
    # H^2=I, so this exponential is exact for this particular Hamiltonian.
    return (math.cos(time) * I - 1j * math.sin(time) * H) @ INITIAL


def qasm(steps=4, time=math.pi / 2):
    if type(steps) is not int or steps <= 0:
        raise ValueError("steps must be a positive integer")
    angle = math.sqrt(2) * time / steps
    lines = ['OPENQASM 2.0;', 'include "qelib1.inc";', 'qreg q[1];', 'creg c[1];']
    for _ in range(steps):
        lines += [f'rx({angle:.17g}) q[0];', f'rz({angle:.17g}) q[0];']
    return '\n'.join(lines + ['measure q -> c;', ''])


def run():
    time = math.pi / 2
    exact = exact_state(time)
    rng = np.random.default_rng(7)
    rows = []
    for steps in (1, 2, 4, 8, 16, 32):
        psi = trotter_state(steps, time)
        probs = np.abs(psi) ** 2
        counts = rng.multinomial(4096, probs / probs.sum())
        rows.append({"steps": steps, "ideal_probability_1": float(probs[1]),
                     "sampled_probability_1": int(counts[1]) / 4096,
                     "counts": {"0": int(counts[0]), "1": int(counts[1])},
                     "state_infidelity": max(0.0, float(1 - abs(np.vdot(exact, psi)) ** 2))})
    return {"time": time, "shots_per_circuit": 4096, "sampling_batches": 6,
            "total_shots": 24576, "seed": 7, "backend": "local_numpy_statevector",
            "exact_probability_1": float(abs(exact[1]) ** 2), "product_formula": rows}


if __name__ == "__main__":
    print(json.dumps(run(), indent=2))

Try a fixed circuit in Marqov

The OpenQASM snapshot fixes t = π/2 and n = 4. Its ideal P(1) is about 0.519465, rather than the exact-evolution value 0.5.

Open Run in Marqov →

Save existing editor work, open Marqov and sign in if required. Set the editor format to OpenQASM and paste a circuit below. Choose an available browser simulator and run explicitly. The link opens the editor; it does not load code or start execution. These tutorial circuits are not in the Examples dropdown.

These Python scripts label bitstrings with q0 on the left. Before comparing editor or native framework output, check the displayed wire and classical-bit order and convert it to the same convention.

hamiltonian-simulation.qasm
OPENQASM 2.0;
include "qelib1.inc";
qreg q[1];
creg c[1];
rx(0.55536036726979576) q[0];
rz(0.55536036726979576) q[0];
rx(0.55536036726979576) q[0];
rz(0.55536036726979576) q[0];
rx(0.55536036726979576) q[0];
rz(0.55536036726979576) q[0];
rx(0.55536036726979576) q[0];
rz(0.55536036726979576) q[0];
measure q -> c;
Download hamiltonian-simulation.qasm

Change one thing

  • Change time to 0 or π/4 and check the exact reference sin²(t)/2.
  • Reverse the rotation order and compare complex states, including the state infidelity, rather than relying only on the Z histogram.

Scope and verification

  • This is a new learning model. The existing QPE demonstration is not relabeled as generic Hamiltonian simulation.
  • The one-qubit system is easy to simulate classically and demonstrates no quantum advantage or many-body research result.
  • More steps increase circuit depth. This ideal local tutorial does not model hardware noise or establish an optimal step count for a device.

Checks compare the Python state and OpenQASM gates with independent mathematical references, including complex phases where needed. Sampling checks use the circuit’s own predicted distribution. Local mathematical checks do not establish hosted or hardware qualification.

Learning tutorial or research replication?

This is a teaching example of time evolution. It is not tied to a claimed paper reproduction. Explore the separate research collection for experiments with retained evidence and scientific scope.

References and provenance

New Marqov teaching model reviewed with the Replications project. No matching Hamiltonian-simulation replication was found; the model is not presented as a replicated paper result.

Learning scope reviewed with the Replications project, October 17, 2026. The local Python scripts and fixed circuit snapshots are separate from the source-pinned twelve-example editor catalog.

Explore all learning tutorials →