Code exampleAdvancedVariational algorithms

VQE for a Two-Qubit Transverse-Field Ising Model

Estimate the ground energy of H = −Z1Z0 − 0.5(X1 + X0) with an n_local ansatz, COBYLA and StatevectorEstimator; the result −√2 matches the exact value.

VQE (Variational Quantum Eigensolver) minimises $\langle\psi(\theta)|H|\psi(\theta)\rangle$ over a parameterised circuit; the variational principle guarantees that the value is never below the ground-state energy. The circuit n_local(2, "ry", "cx", reps=2) has 6 parameters. The exact value for two sites is $-\sqrt{J^2+4h^2}=-\sqrt2$. For large systems the exact value is not known, and the optimiser may get stuck or the gradients may vanish.

Requirements: pip install qiskit scipy numpy. The code runs on your machine or in Colab, not inside WordPress.

Code

Qiskit
import numpy as np
from scipy.optimize import minimize
from qiskit.circuit.library import n_local
from qiskit.quantum_info import SparsePauliOp
from qiskit.primitives import StatevectorEstimator

H = SparsePauliOp.from_list([("ZZ", -1.0), ("XI", -0.5), ("IX", -0.5)])
exact = np.linalg.eigvalsh(H.to_matrix()).min()

ansatz = n_local(2, "ry", "cx", entanglement="linear", reps=2)
estimator = StatevectorEstimator()


def energy(x):
    return float(estimator.run([(ansatz, H, x)]).result()[0].data.evs)


x0 = np.full(ansatz.num_parameters, 0.1)
res = minimize(energy, x0, method="COBYLA", options={"maxiter": 300})
print("parameters:", ansatz.num_parameters)
print("VQE energy  :", round(res.fun, 6))
print("exact energy:", round(float(exact), 6), "= -sqrt(2):", round(-np.sqrt(2), 6))

Line-by-line code explanation

LineExplanation
1-5Imports: numpy, scipy, the parameterised circuit, SparsePauliOp and the estimator.
7The Hamiltonian with three Pauli terms.
8The exact ground-state energy by diagonalisation.
10An RY circuit with linear CNOTs, two repetitions.
11The estimator.
14-15The energy function: the expectation value for parameters x.
18A fixed starting point.
19Minimise with COBYLA.
20-22Print the number of parameters and the two energies.

Expected output (from an actual run)

parameters: 6
VQE energy  : -1.414214
exact energy: -1.414214 = -sqrt(2): -1.414214

The output is deterministic (fixed starting point and exact computation).

Related topics

References

  1. Alberto Peruzzo et al. (2014). A variational eigenvalue solver on a photonic quantum processor. Nature Communications 5:4213 doi:10.1038/ncomms5213
  2. M. Cerezo et al. (2021). Variational quantum algorithms. Nature Reviews Physics 3:625–644 doi:10.1038/s42254-021-00348-9
  3. IBM Quantum (2025). Qiskit SDK API documentation. IBM Quantum Documentation quantum.cloud.ibm.com