Independently re-derived in Python/sympy, following the physical setup described in
simpleHarmonicOscillator/ of
Kelly’s Lagrange_Mechanics_Derivations
(MATLAB + Symbolic Math Toolbox there; sympy here). This is the “hello world” of the gallery:
the simplest possible sanity check for the lagrange_equations() helper used throughout the
rest of this folder, and for Chapter 9’s
Hessian-based extraction.
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
from scipy.integrate import solve_ivp
plt.rcParams["figure.figsize"] = (7, 4.0)
plt.rcParams["axes.grid"] = True
def lagrange_equations(L, qs, t, Q=None):
"""Euler-Lagrange equations d/dt(dL/dqdot_i) - dL/dq_i = Q_i, one per generalized coordinate."""
if Q is None:
Q = [0] * len(qs)
eqs = []
for qi, Qi in zip(qs, Q):
qid = sp.diff(qi, t)
eqs.append(sp.expand(sp.diff(sp.diff(L, qid), t) - sp.diff(L, qi) - Qi))
return eqs
def solve_for_accelerations(eqs, qs, t):
"""Given Euler-Lagrange residual equations (=0) and coordinates, solve the linear-in-\\ddot q
system for the accelerations symbolically: returns (M, f, qddot_exprs) with M*qddot + f = 0."""
qdd = [sp.diff(qi, t, 2) for qi in qs]
M = sp.Matrix([[sp.diff(eq, a) for a in qdd] for eq in eqs])
f = sp.Matrix([eq.subs({a: 0 for a in qdd}) for eq in eqs])
sol = M.solve(-f)
return M, f, solt = sp.symbols("t")
m, k = sp.symbols("m k", positive=True)
x = sp.Function("x")(t)
T = sp.Rational(1, 2) * m * sp.diff(x, t) ** 2
V = sp.Rational(1, 2) * k * x**2
L = T - V
eqs = lagrange_equations(L, [x], t)
print("Euler-Lagrange residual (=0):", eqs[0])
M, f, qdd_sol = solve_for_accelerations(eqs, [x], t)
print("M =", M, " f =", f, " => xddot =", qdd_sol[0])Euler-Lagrange residual (=0): k*x(t) + m*Derivative(x(t), (t, 2))
M = Matrix([[m]]) f = Matrix([[k*x(t)]]) => xddot = -k*x(t)/m
As expected: , i.e. — simple harmonic motion with .
m_val, k_val = 1.0, 4.0
wn = np.sqrt(k_val / m_val)
rhs = sp.lambdify((x, m, k), qdd_sol[0], "numpy")
def deriv(_t, y):
xx, xd = y
return [xd, rhs(xx, m_val, k_val)]
sol = solve_ivp(deriv, [0, 10], [1.0, 0.0], max_step=0.01, dense_output=True)
tt = np.linspace(0, 10, 800)
xx = sol.sol(tt)[0]
plt.plot(tt, xx, label="sympy-derived EOM, numerically integrated")
plt.plot(tt, np.cos(wn * tt), "--", label=r"closed form $\cos(\omega_n t)$")
plt.xlabel("t [s]"); plt.ylabel("x(t)")
plt.title(f"SHO check: $\\omega_n$={wn:.4f} rad/s")
plt.legend()
plt.show()