Simulating pendulum with lagrangian mechanics

Lagrangian equation: \(\frac{d}{dt}\frac{\partial \mathcal{L}}{\partial \dot{x}}-\frac{\partial \mathcal{L}}{\partial x} = 0\)
Where \(\mathcal{L}\) is langrangian operator, we can calculate lagrangian oprator like this: \(L = T-V\)
Where \(T\) is kinetic energy and \(V\) is potential energy.
triangle with all three sides equal

Pendulum

Position of end of the pendulum is described by angle \(\varphi\) and length of the beam \(l\).
Equation for calculating kinectic energy is \(T = \frac{1}{2}mv^2\) and equation for potential is \(V = mgh\).
Postion of ball in cartesian coordinates is described with vertical position \(y\) and horisontal position \(x\).
\(y = -l\cos(\varphi), x = l\sin(\varphi)\).
Potential energy is then \(V = mgy = -mgl\cos(\varphi)\).
For kinetic energy speed has to be calculated like this: \(v = \sqrt{\dot{x}^2+\dot{y}^2}\).
Calculating \(x\) and \(y\) derivatives. \(\dot{x} = l\dot{\varphi}\cos(\varphi), \dot{y}=l\dot{\varphi}\sin(\varphi)\).
So kinetic energy is \(T = \frac{1}{2}m(l^2\dot{\varphi}^2\cos(\varphi)^2+l^2\dot{\varphi}^2\sin(\varphi)^2)=\frac{1}{2}ml^2\dot{\varphi}^2\)
Now substitute to Lagrangian \(L = T-V = \frac{1}{2}ml^2\dot{\varphi}^2+mgl\cos(\varphi)\)

Substituting into Lagrangian equation

\(\frac{\partial \mathcal{L}}{\partial \dot{\varphi}}=m\dot{\varphi}l^2\)
\(\frac{d}{dt}\frac{\partial \mathcal{L}}{\partial \dot{\varphi}}=m\ddot{\varphi}l^2\)
\(\frac{\partial \mathcal{L}}{\partial \varphi} = -mgl\sin(\varphi)\)
\(\begin{aligned} m\ddot{\varphi}l^2+mgl\sin(\varphi) &= 0 \\ \ddot{\varphi}+\frac{g}{l}\sin(\varphi) &= 0 \end{aligned}\)
Now we have obtained diferencial equation for simple pendulum. Notice that it doesn't depend on weight of the ball. Substituting angular velocity \(\omega = \dot{\varphi}\) we get:
\(\begin{aligned} \dot{\varphi} &= \omega \\ \dot{\omega} &= -\frac{g}{l}\sin(\varphi) \end{aligned}\)
We can solving it using Range kuta (RK4) metodth

Range kuta for solving diferential equations

\(\begin{aligned} k_1 &= f(t_n, y_n) \\ k_2 &= f\left(t_n +\frac{h}{2}, y_n + \frac{k_1}{2}\right) \\ k_3 &= f\left( t_n+\frac{h}{2}, y_n+h\frac{k_2}{2} \right) \\ k_4 &= f(t_n+h, y_n + hk_3)\\ \\ y_{n+1} &= y_n+\frac{h}{6}(k_1+2k_2+2k_3+k_4) \\ t_{n+1} &= t_n +h \end{aligned}\)

Visualising the pendulum

Gravity (g) \([ m/s^2 ]\)
Length (l) \([cm]\)