I am working on a javascript-web based simulation of a spring-cart-pendulum system in order to apply some math I've recently learned into a neat small project. I found a sample image on the internet as to what I am trying to model:
I understand how to derive the equations of motions by finding the Lagrangian and then from there deriving the Euler–Lagrange equations of motion:
Given that the mass of cart is $M$ and mass of ball on pendulum is $m$, length of pendulum $l$, distance of cart from spring (with constant $k$) equilibrium $x$ and pendulum angle $\theta$ we have the following equations of motion:
$$x'' cos(\theta) + l\theta'' – gsin(\theta) = 0$$
$$(m+M)x''+ml[\theta''cos(\theta) – (\theta')^2sin(\theta)] = -kx$$
(A derivation can be found here, although this is not the point of the question ).
I have isolated the equations for $x''$ and $\theta''$ as follows:
$$x'' = \frac{-kx – ml[-sin(\theta)(\theta')^2-\frac{g}{l} cos(\theta)sin(\theta)]}{m+M – mcos^2(\theta)}$$
$$\theta'' = \frac{-gsin(\theta)-cos(\theta)x''}{l}$$
I then used Euler's method by using previous/initial conditions to solve for $x''$ and then for $\theta''$ (since it depends on $x''$. I then solved for $x' = x''t + x'$, $x = x't + x$ (likewise for $\theta$), where $t$ is the stepsize.
This approach seems to work well for initial conditions where $\theta$ or $\theta'$ is small (have yet to test playing around with $x$'s). However, when I set the $\theta$'s to bigger values, then my spring goes crazy and all over the screen.
Now I have never physically set up a spring-cart-pendulum system so maybe my simulation is correct ( although I have my doubts), but I was wondering what other methods I can use for numerical and more accurate approximation. I could always set the step size for Euler approximation to something smaller, but that would effect the speed and functionality of my simulation.
I have heard about things like Runge–Kutta but not sure how to apply it to a second order system of DEs. Does anyone have any advice, reading or examples that I can look at to learn from for more accurate approximation?
Thank you for your time.
Cheers,
Best Answer
You can always transform a system of higher order into a first order system where the sum over the orders of the first gives the dimension of the second.
Here you could define a 4 dimensional vector $y$ via the assignment $y=(x,θ,x',θ')$ so that $y_1'=y_3$, $y_2'=y_4$, $x_3'=$ the equation for $x''$ and $y_4'=$ the equation for $θ''$.
In python as the modern BASIC, one could implement this as
and then pass it to an ODE solver by some variant of
The readily available solvers are
Or you build your own
and then call it and print the solution as
Or plot it
where with initial values and constants
I get this artful graph: