This post is dedicated to the beautiful chaos created by double pendulums. I have seena great variety of animated versions, implemented with different tool but never in R.Thanks to the amazing package gganimate
, it is actually not that hard to produce them in R.
1 |
|
I am not going to attempt to explain the math behind the double pendulum. If you are interestedin the details, check out a complete walkthrough here.The code presented here is a straightforward adaption from python.
First, we need to set up some basic constants and the starting conditions.
1 |
|
These are the parameters you need to change in order to produce differentpendulums. Just experiment a little!
The partial derivatives needed can be calculated with the following function.
1 |
|
This function needs to be integrated. Luckily, there is the odeintr
packages that does the job.The start
, duration
and step_size
parameters control the time for your pendulum.In the below example, I choose to “swing” the pendulum for 30 seconds and the positionis recalculated every 0.1 seconds.
1 |
|
Now we just need to compute the x and y coordinates for both pendulums from theangles (\theta) obtained from the integration.
1 |
|
The final data frame contains the exact position of the pendulums for each time step.Animating the pendulums is straightforward with the package gganimate
.
1 |
|
We can also add some more details to the animation, like the trail of the second pendulum to track its path.It turned out to be a bit more tricky then expected though. The trail needs to be added via asecondary data.frame so that it can be animated with the transition_time()
.I used the lag()
function to compute the trail from the last five time points.
1 |
|
I used the shadow_mark()
function to keep the past trails.
1 |
|
That’s it. Now you can play around with the constants (L1,L2,M1,M2,G
) and the initial conditions(th1,w1,th2,w2
) to create your own chaotic pendulums.
Below is my personal favorite. 40 pendulums with nearly identical starting conditions.Watch how quickly their paths diverge into pure chaos.
Related