Case study: a pendulum, from physics to PINN
One simple machine, every idea in this book: a differential equation from Newton's law, a numerical solver, a neural network trained on measurements, and a physics-informed network that needs far fewer of them.
Hang a weight on a string and let it swing. Physics gives us a rule for how the angle changes. A computer can follow that rule step by step. A neural network can instead learn the swing from measurements — but only where it has measurements. A PINN learns from a few measurements and the rule, so it keeps swinging correctly long after the data stop.
1. The physics: Newton's law becomes an ODE

A bob of mass $m$ hangs on a light rod of length $L$. Let $\theta(t)$ be the angle from the vertical. Gravity pulls with force $mg$; its component along the path of the bob is $-mg\sin\theta$. The bob moves along a circle, so its acceleration along the path is $L\theta''$. Newton's second law (mass × acceleration = force) gives $$mL\,\theta'' = -mg\sin\theta \quad\Longrightarrow\quad \boxed{\;\theta''(t) + \frac{g}{L}\sin\theta(t) = 0,\qquad \theta(0) = \theta_0,\ \ \theta'(0) = 0.\;}$$ The mass cancels: a heavy and a light bob swing the same way. This is a second-order, nonlinear ODE with two initial conditions.
For small angles, $\sin\theta \approx \theta$ (at $10^\circ = 0.1745$ rad, $\sin\theta = 0.1736$ — a 0.5 % difference). The equation becomes $\theta'' + \omega^2\theta = 0$ with $\omega = \sqrt{g/L}$, whose solution is $\theta(t) = \theta_0\cos(\omega t)$. One full swing takes $$T_0 = \frac{2\pi}{\omega} = 2\pi\sqrt{\frac{L}{g}}.$$ For $L = 1$ m and $g = 9.81$ m/s²: $T_0 = 2\pi\sqrt{1/9.81} \approx 2.006$ s. A one-metre pendulum ticks almost exactly once per second each way — which is why grandfather clocks are about a metre long.
For large swings the period grows: at $\theta_0 = 30^\circ$ it is 1.7 % longer than $T_0$, at $60^\circ$ 7.3 % longer, and at $80^\circ$ about 14 % longer (the exact value involves an elliptic integral). That is where the small-angle model fails, and where solving the full nonlinear equation matters.
2. The classical way: step through time

Write the equation as a first-order system for angle and angular velocity, $\theta' = v$, $v' = -\frac{g}{L}\sin\theta$, then step with Runge–Kutta 4 or SciPy's solve_ivp. With a small step this is extremely accurate and fast — this is the reference ("ground truth") against which we will judge every neural network.
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
g, L = 9.81, 1.0
def rhs(t, y): # y = [theta, v]
return [y[1], -g / L * np.sin(y[0])]
t = np.linspace(0, 6, 600)
for deg in [10, 60, 120]:
sol = solve_ivp(rhs, [0, 6], [np.radians(deg), 0], t_eval=t, rtol=1e-9)
plt.plot(t, sol.y[0], label=f"start at {deg}°")
plt.xlabel("time t (s)"); plt.ylabel("angle θ (rad)"); plt.legend(); plt.title("Larger swings take longer")
plt.show()
3. The vocabulary of machine learning, on one pendulum
| Word | Meaning | On the pendulum |
|---|---|---|
| Input / output | what the model reads / predicts | time $t$ → angle $\theta(t)$ |
| Training data | examples used to fit the weights | angles measured during the first second (blue dots in the lab) |
| Test data | examples never shown during training, used to judge the model | true angles at other times, including later times (hollow violet dots) |
| Collocation points | points where a PINN checks the equation; no measurement needed | orange ticks along the time axis |
| Initial-condition points | where the PINN is told the starting state | $\theta(0) = \theta_0$, $\theta'(0) = 0$ |
| Loss | one number measuring how wrong the model is | data misfit + equation residual + initial-condition misfit |
| Iteration / epoch | one update of the weights / one pass through all data | the counter in the lab |
| Training error | error on the training data | how well the curve passes through the blue dots |
| Test error | error on unseen data — the honest score | how well the curve matches the truth at the violet dots |
| Interpolation / extrapolation | predicting inside / outside the range of the data | $t < 1$ s / $t > 1$ s |
| Accuracy | for numbers we usually report an error (root-mean-square, maximum, or relative %); "accuracy" in % is mainly used for classification | e.g. test error 0.02 rad ≈ 1° |
4. The lab: data-only network vs PINN

Now do it yourself. Both networks below have the same architecture (one hidden layer of 32 tanh neurons), the same starting weights and the same optimiser (Adam). The data-only network minimises only the misfit to the measurements. The PINN minimises $$\mathcal L(\theta_{\text{net}}) = \underbrace{\frac{1}{N_c}\sum_{j}\Big(u''(t_j) + \tfrac{g}{L}\sin u(t_j)\Big)^2}_{\text{physics, at collocation points}} + \underbrace{\lambda\Big[(u(0)-\theta_0)^2 + u'(0)^2\Big]}_{\text{initial conditions}} + \underbrace{\frac{\lambda_d}{N_d}\sum_k \big(u(t_k) - y_k\big)^2}_{\text{data}},$$ with the derivatives $u'$, $u''$ of the network computed exactly. Here $g/L = \pi^2$, so a small swing takes 2 s.
- Default settings. Both networks fit the blue dots (small training error). Only the PINN has a small test error. That is the difference between memorising and learning.
- Measurements = 2. The data-only network is hopeless; the PINN still works, because the initial conditions and the equation carry almost all the information.
- Data window = 3 s. Now the data cover the whole range: the data-only network improves a lot. Data can replace physics — if you have enough of it, everywhere you need it.
- Noise = 0.15. The data-only network bends to follow the noisy dots (overfitting). The PINN is held close to the law.
- Collocation points = 10. Too few checks of the equation: the PINN can cheat between them. Raise to 60 again.
- Time span = 5 s. PINN training gets much harder over long times — errors at early times propagate. This is a real, known difficulty (see Chapter 16, section 4); remedies include training on growing time windows.
- Starting angle = 120°. Strongly nonlinear motion. The PINN uses the full $\sin\theta$, so it still follows the truth.
5. Underfitting and overfitting, seen on the pendulum
The general ideas are in Chapter 15. On the pendulum:
- Underfitting: a network with 2 neurons cannot even bend through all the measurements — training error stays high.
- Overfitting: with noisy measurements, a flexible data-only network threads through every noisy dot; training error near zero, test error large.
- Extrapolation failure is not overfitting: the data-only network may fit the data window perfectly and honestly — it simply has no information about later times.
- The physics loss acts as a regulariser: it removes wiggles that break the equation, reducing variance without biasing the answer (if the equation is right).
In the lab, the data-only network has training error 0.004 and test error 0.9. Which statement is best?
Right. A tiny training error with a large test error means the model learned the training set, not the law. Here the main cause is extrapolation beyond the data window.
6. The inverse problem: learn $g/L$ from measurements
Suppose you do not know the length of the string. Make $k = g/L$ a trainable number next to the network weights, and minimise the same loss with the residual $u'' + k\sin u$. If the measurements are informative, $k$ converges to the true value — from which $L = g/k$. This is a PINN doing what classical solvers cannot do directly: solving the equation and identifying its coefficient in one optimisation (see Chapter 16, section 3).
import math, torch
torch.manual_seed(0)
# --- synthetic measurements from the true pendulum (g/L = pi^2, start at 60 degrees)
k_true, th0 = math.pi**2, math.radians(60)
def rk4(k, T=3.0, n=3000):
h, y, out = T / n, torch.tensor([th0, 0.0]), []
f = lambda y: torch.stack([y[1], -k * torch.sin(y[0])])
for i in range(n + 1):
out.append(y[0].item())
k1 = f(y); k2 = f(y + h/2*k1); k3 = f(y + h/2*k2); k4 = f(y + h*k3)
y = y + h/6*(k1 + 2*k2 + 2*k3 + k4)
return torch.tensor(out)
truth = rk4(k_true)
t_data = torch.linspace(0.1, 1.5, 12).reshape(-1, 1)
y_data = truth[(t_data[:, 0] / 3.0 * 3000).round().long()].reshape(-1, 1)
y_data += 0.01 * torch.randn_like(y_data) # measurement noise
# --- network u(t) and the unknown coefficient k (log-parametrised to stay positive)
net = torch.nn.Sequential(torch.nn.Linear(1, 32), torch.nn.Tanh(),
torch.nn.Linear(32, 32), torch.nn.Tanh(),
torch.nn.Linear(32, 1))
log_k = torch.nn.Parameter(torch.tensor(math.log(5.0))) # deliberately wrong guess
opt = torch.optim.Adam(list(net.parameters()) + [log_k], lr=1e-3)
t_col = torch.linspace(0, 3.0, 200).reshape(-1, 1).requires_grad_(True)
t0 = torch.zeros(1, 1, requires_grad=True)
for it in range(15000):
u = net(t_col)
u_t = torch.autograd.grad(u, t_col, torch.ones_like(u), create_graph=True)[0]
u_tt = torch.autograd.grad(u_t, t_col, torch.ones_like(u_t), create_graph=True)[0]
res = u_tt + torch.exp(log_k) * torch.sin(u) # the pendulum equation
u0 = net(t0)
u0_t = torch.autograd.grad(u0, t0, torch.ones_like(u0), create_graph=True)[0]
loss = (res**2).mean() + 10*((u0 - th0)**2 + u0_t**2).sum() + 10*((net(t_data) - y_data)**2).mean()
opt.zero_grad(); loss.backward(); opt.step()
if it % 3000 == 0:
print(f"iter {it:5d} loss {loss.item():.2e} k = {torch.exp(log_k).item():.3f}")
print(f"learned g/L = {torch.exp(log_k).item():.3f} (true {k_true:.3f})")
print(f"=> string length L = {9.81 / torch.exp(log_k).item():.3f} m (true {9.81 / k_true:.3f} m)")
Replace the pendulum by heat in a rod, flow in an oil reservoir, or a chemical reaction in a catalyst pellet, and the story is the same: a few expensive measurements, a trusted law with unknown coefficients, and a network that combines the two. When you need the answer for thousands of different starting angles or coefficients, train an operator network instead of one PINN per case.
- Newton's law gives $\theta'' + \frac{g}{L}\sin\theta = 0$; small swings have period $2\pi\sqrt{L/g}$.
- A classical solver (RK4) is the accurate reference for a single forward problem.
- A data-only network can fit its training data and still fail on test data, especially outside the data window.
- A PINN uses collocation points (no data needed) to enforce the law, so it extrapolates and resists noise.
- PINNs can also learn unknown coefficients such as $g/L$ — an inverse problem.
- PINNs are not magic: long time spans and stiff problems make training hard.
Further reading
- S. H. Strogatz, Nonlinear Dynamics and Chaos, 2nd ed., CRC Press, 2015 — chapter 6 (the pendulum in the phase plane).
- M. Raissi, P. Perdikaris & G. E. Karniadakis, "Physics-informed neural networks", J. Comput. Phys. 378, 2019, 686–707.
- S. Wang, S. Sankaran & P. Perdikaris, "Respecting causality for training physics-informed neural networks", CMAME 421, 2024, 116813 (why long time spans are hard).
- S. Greydanus, M. Dzamba & J. Yosinski, "Hamiltonian neural networks", NeurIPS 2019 (learning a pendulum that conserves energy).