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.
Define a new variable "Tperiod" that you initialize to the value 0.
Because you detect the end of the period by the sign of "omega" you have to declare another variable omega2 that you put in at the end of your Loop. You can write omega2=omega to save the last value of Omega in another value.
In your loop "while (t <= tmax)" you insert the following if-condition:
"if (omega2/abs(omega2)<0 AND omega/abs(omega) > 0) then Tperiod = t".
Here the function $\frac{\omega}{|\omega|}=Omega/abs(omega)$ is the Signum function.