Skip to content

Instantly share code, notes, and snippets.

@iscadar
Created July 7, 2012 10:47
Show Gist options
  • Save iscadar/3065820 to your computer and use it in GitHub Desktop.
Save iscadar/3065820 to your computer and use it in GitHub Desktop.
A pendulum simulation using fourth order Runge-Kutta integration
from scipy import *
from matplotlib.pyplot import *
##A pendulum simulation using fourth order
##Runge-Kutta integration
##v0.1
##Alexandros Kourkoulas Chondrorizos
ts=.05 #time step size
td=40 #trial duration
te=int(td/ts) #no of timesteps
mu=0.1 #friction factor
m=1 #mass
g=9.81 #grav. acceleration
l=1 #length
th=[pi/4]#((rand()*2)-1)*pi] #initial angle
om=[0] #initial angular velocity
u=0 #torque
for j in range(te):
#Euler approximation
th.append(th[j] + ts*om[j])
f1 = (-mu*om[j] + m*g*l*sin(th[j]) + u)/(m*(l^2))
om.append(om[j] + ts*f1)
#approximation 1 at mid-interval
th2 = th[j+1] + (ts/2)*om[j+1]
f2 = (-mu*om[j+1] + m*g*l*sin(th[j+1]) + u)/(m*(l^2))
om2 = om[j+1] + (ts/2)*f2
#approximation 2 at mid-interval
th3 = th2 + (ts/2)*om2
f3 = (-mu*om2 + m*g*l*sin(th2) + u)/( m*(l^2))
om3 = om2 + (ts/2)*f3
#approximation at next time step
th4 = th3 + (ts)*om3
f4 = (-mu*om3 + m*g*l*sin(th3) + u)/( m*(l^2))
om4 = om3 + (ts)*f4
dth=(om[j] + 2*om[j+1] + 2*om2 + om3)/6
dom=(f1 + 2*f2 + 2*f3 + f4)/6
th[j+1] = th[j] + ts*dth
om[j+1] = om[j] + ts*dom
subplot(211),plot(th),xlabel('Angle'),ylabel('')
subplot(212),plot(om,'r'),xlabel('Angular velocity'),ylabel('')
show()
@Stewori
Copy link

Stewori commented May 4, 2015

Something with the plot(?) seems to be wrong, please correct me if I interpret it incorrectly:
If I run this example, the angle-plot seemingly fades out to Pi, but shouldn't it be 0?
"Angle" refers to the deflection of the pendulum from its idle-position, doesn't it?
And indeed, if I replace the initial angle of Pi/4 by 0, i.e. idle position the pendulum resides there, giving a constant-0 angle plot.
So, is Pi equivalent to 0 here? I would interpret 2Pi as the next-period idle position (a full turn), or is the pendulum Pi-periodic? Or is there some bug?
Is there an initial angle that will let the pendulum end up at 0?

@wilcooo
Copy link

wilcooo commented Jul 9, 2018

@Stewori
In this script, an angle of 0 is chosen to be at the top (yes, it is more convenient to choose 0 at the bottom, but this works too)

The reason why choosing an initial angle of 0 yields a constant-0 angle plot is that it can stand exactly upright without movement, try choosing 0.00001 and you'll see it fall down to pi eventually.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment