Example: Pendulum

In this example, we will simulate the motion of a pendulum using Newton's second law in polar coordinates. Applying Newton's second law gives:

$$\ddot{\phi}=-\frac{g}{R}\sin(\phi)$$

We can update $\dot{\phi}$ using the approximation

$$\dot{\phi}=\dot{\phi} + \ddot{\phi}\Delta t$$

We can update ${\phi}$ using the approximation

$$\phi = \phi + \dot{\phi}\Delta t$$

Note that this is the angle the string makes with the $-y$ axis. Thus the position of the pendulum is

$$\vec{r}=<R\cos(\phi),-R\sin(\phi),0>$$

Assume that the radius of the pendulum is 1 m and it starts from rest.


In [ ]:
from __future__ import division, print_function
from ivisual import *
from math import *

In [1]:
scene = canvas(title='Pendulum')

#length of pendulum
R=1

#initial angle with respect to -y axis
phi_deg=45
phi=phi_deg*pi/180 #phi in rad

#gravitational field in N/kg
g=9.8

#initial angular velocity
phidot=0  #rad/s

t=0
dt=0.01

#position vector
r=R*vector(sin(phi),-cos(phi),0)

pendulum=sphere(pos=r, radius=R/15, color=color.yellow)
rarrow=arrow(pos=(0,0,0), axis=r, shaftwidth=R/25, color=color.orange)

while t<5:
    rate(100)
    
    #update phidotdot, phidot, phi
    phidotdot=-g/R*sin(phi)
    phidot=phidot+phidotdot*dt
    phi=phi+phidot*dt
    
    #update r
    r=R*vector(sin(phi),-cos(phi),0)
    pendulum.pos=r
    rarrow.axis=r
    
    t=t+dt



In [6]:


In [ ]: