01 · Classical mechanics¶
Newton's second law for a pendulum of length $L$ gives
$$\ddot\theta = -\frac{g}{L}\sin\theta .$$
For small angles $\sin\theta\approx\theta$ and the period is $T_0 = 2\pi\sqrt{L/g}$. How wrong is that at large amplitude?
In [1]:
# Setup: installs the qplay package if it is missing (for example on Google Colab).
import importlib.util, subprocess, sys
if importlib.util.find_spec("qplay") is None:
subprocess.run([sys.executable, "-m", "pip", "install", "-q",
"quantum-playground"], check=True)
In [2]:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
from qplay import mechanics, integrators, symbolic
Period versus amplitude¶
The exact period is $T = 4\sqrt{L/g}\,K\!\left(\sin^2\tfrac{\theta_0}{2}\right)$, with $K$ the complete elliptic integral of the first kind.
In [3]:
theta0 = np.linspace(0.01, 3.1, 200)
T = mechanics.pendulum_period(theta0)
T0 = 2 * np.pi * np.sqrt(1 / 9.81)
plt.plot(theta0, T / T0)
plt.xlabel(r"amplitude $\theta_0$ [rad]"); plt.ylabel(r"$T / T_0$")
plt.title("Pendulum period grows with amplitude");
Chaos in a double pendulum¶
Two double pendulums that differ by $10^{-6}$ rad at the start.
In [4]:
for eps in (0, 1e-6):
t, y = mechanics.double_pendulum([2.0, 2.0 + eps, 0, 0], t_max=25, n=2500)
plt.plot(t, y[:, 1], label=f"eps = {eps:g}")
plt.xlabel("t [s]"); plt.ylabel(r"$\theta_2$"); plt.legend();
From a Lagrangian to a simulation¶
Give SymPy the Lagrangian $L = T - V$ and it derives the equations of motion from
$$\frac{d}{dt}\frac{\partial L}{\partial \dot q} - \frac{\partial L}{\partial q} = 0 .$$
In [5]:
t, m, l, g = sp.symbols("t m l g", positive=True)
th = sp.Function("theta")(t)
L = m * l**2 * sp.diff(th, t)**2 / 2 + m * g * l * sp.cos(th)
sp.Eq(sp.Symbol(r"\ddot\theta"), symbolic.accelerations(L, [th], t)[0])
Out[5]:
$\displaystyle \ddot\theta = - \frac{g \sin{\left(\theta{\left(t \right)} \right)}}{l}$
In [6]:
rhs = symbolic.to_numeric_rhs(L, [th], t, {m: 1, l: 1, g: 9.81})
tt, y = integrators.solve(rhs, [1.0, 0.0], (0, 10), n=500)
plt.plot(tt, y[:, 0]); plt.xlabel("t [s]"); plt.ylabel(r"$\theta$");
Your turn¶
- Compare
integrators.euler,rk4andvelocity_verleton a long oscillator run. Which one drifts in energy? - Add a spring to the Lagrangian above and watch the motion change.
- Try
mechanics.nbodywith your own initial conditions.