I'm writing a short program to simulate a simple pendulum. The equations of motion are
$$\frac{d\theta}{dt}=\omega$$ $$\frac{d\omega}{dt}=-\frac{g}{r}\sin\theta$$
For some small time step $dt$ the time evolution of $\theta$ and $\omega$ are governed by
$$\theta\left(t+dt\right)=\theta\left(t\right)+\omega\left(t\right)dt$$ $$\omega\left(t+dt\right)=\omega\left(t\right)-\frac{g}{r}\sin\left[\theta\left(t+dt\right)\right]dt$$
Assuming a small initial amplitude, the period of oscillation is
$$T=2\pi\sqrt{\frac{r}{g}}$$
Here is the python code I came up with, which works well
from numpy import *
file = open('task15.txt', 'w')
file.write("time" + "\t" + "theta" + "\t" + "omega" + "\n")
t = 0.0
tmax = 20.0
dt = 0.1
theta = 0.1
omega = 0.0
while (t <= tmax):
theta += omega * dt
omega -= sin(theta) * dt #choose units such that (g/r) = 1
file.write(str(t) + "\t" + str(theta) + "\t" + str(omega) "\n")
t += dt
file.close()
exit()
By plotting the amplitude as a function of time, I have found graphically that the period asymptotically increases from the expected value (given above) as the initial amplitude increases, because the small angle approximation no longer holds.
I would like to update the code so it can calculate the period, although I'm not sure how to do this explicitly.
Somehow I need to create a user-defined function which returns the time when $\theta$ changes sign. Can I do this using the while loop? Then the difference between two successive times is half the period.
Can someone push me in the right direction with an algorithm and/or code? Thanks in advance.