I'm trying to plot how the angle θ and angular velocity ω vary with respect to time t for a linear and non-linear pendulum using the trapezoid rule to solve for the differential equations, but I'm having trouble generating the actual plot.
This is the code I'm trying to implement for the linear pendulum with no frictional dampening or driving force where θ is initialised to 0.2 and ω to 0.0
import matplotlib.pylab as plt
import math
theta = 0.2 #angle
omega = 0.0 #angular velocity
t = 0.0 #time
dt = 0.01
nsteps = 0
k = 0.0 #dampening coefficient
phi = 0.66667 #angular frequency of driving force
A = 0.0 #amplitude of driving force
#2nd order ODE for linear pendulum
def f(theta, omega, t):
return -theta - k*omega + A*math.cos(phi*t)
#trapezoid rule
for nsteps in range(0,1000):
k1a= dt*omega
k1b = dt*f(theta, omega, t)
k2a = dt*(omega + k1b)
k2b = dt*f(theta + k1a, omega + k1b, t + dt)
theta = theta + (k1a + k2a)/2
omega = omega + (k1b + k2b)/2
t = t + dt
nsteps = nsteps + 1
plt.plot(t, theta)
plt.plot(t, omega)
plt.axis([0, 500, -math.pi, math.pi])
plt.title('theta = 0.2, omega = 0.0')
plt.show()
I've worked out the values for the first few iterations through the for loop by hand and it seems to behave as it should do, but the plot just gives me nothing:
I know it should get a sinusoid, so I think it might just be an issue with how I'm trying to generate the plot.
Any help would be much appreciated.