A differentiable variational circuit in PennyLane

MediumQuantum Machine LearningQuantum machine learning

Goal: Optimising the parameters of a quantum circuit by gradient.

Python — example.py
import pennylane as qml
from pennylane import numpy as np

dev = qml.device("default.qubit", wires=2)

@qml.qnode(dev)
def circuit(w):
    qml.RX(w[0], wires=0); qml.RY(w[1], wires=1)
    qml.CNOT(wires=[0, 1])
    return qml.expval(qml.PauliZ(1))

w = np.array([0.1, 0.2], requires_grad=True)
opt = qml.GradientDescentOptimizer(stepsize=0.4)
print(f"Before: {circuit(w):.4f} | gradient: {np.round(qml.grad(circuit)(w), 4)}")
for _ in range(40):
    w = opt.step(circuit, w)
print(f"After 40 steps: {circuit(w):.4f}")

Code explanation

We define a quantum node (QNode) on the default.qubit simulator and compute the expectation value of PauliZ. PennyLane computes the gradient with the parameter-shift rule, and we use an optimizer to drive the expectation value towards -1.

Requirements

Shell
pip install pennylane

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

Before: 0.9752 | gradient: [-0.0978 -0.1977]
After 40 steps: -1.0000

This example was actually run and tested on 21 November 2026 on a CPU — pennylane 0.45.1, python 3.13.18

Libraries used

Related examples