Week 3 - Solving second order ODEs
Simple Pendulum:
The lenght of the pendulum is 1m, the mass of the ball is considered to be 1kg, and the damping coeff is 0.05. The time span under consideration is 0-20sec, which is sub divided into 150 points. The initial angular velocity is considered to be 3rad/s.
So in the python code.
Initial condition comprises of angular distance of 0rad, and angular velocity as 3rad/s.
The code begins with the definition of the function to solve the ODE, where the two ODEs are solved, with the help of the input variables. Then comes the plotting part, where first the angular displacement and the angular velocity are being plotted with respect to time. Second plot when stitched together results in an animation of the pendulum motion. The code is as shown:
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
def model(Theta,t,b,length,gravity,mass):
Theta1= Theta[0]
Theta2 = Theta[1]
dTheta1_dt = Theta2
dTheta2_dt = -(b/mass)*Theta2 -(gravity/length)*math.sin(Theta1)
dTheta_dt = [dTheta1_dt, dTheta2_dt]
return dTheta_dt
# inputs
b = 0.05
length = 1
gravity = 9.81
mass = 1
# initial conditions
Theta_x = [0,3]
# time points
t = np.linspace(0,20,150)
# solve ode
Theta = odeint(model,Theta_x,t,args=(b,length,gravity,mass))
# plot
plt.plot(t, Theta[:,0], 'r-',label='Displacement')
plt.plot(t, Theta[:,1], 'b--',label='Velocity')
plt.ylabel('plot')
plt.xlabel('time')
plt.legend()
plt.legend(loc='best')
plt.show()
# animation
X = Theta[:, 0]
ct = 1
for theta in X:
x1 = 0
y1 = 0
x2 = length*math.sin(theta)
y2 = -(length*math.cos(theta))
file = 'pendulum%05d.png'%ct
plt.figure()
plt.plot([0, 0], [-1.5, 1.5], 'k--')
plt.plot([-1.5, 1.5], [0, 0],'k-', linewidth=5)
plt.plot([x1, x2], [y1, y2],'k-', linewidth=5)
plt.plot(x2, y2, 'm o', markersize=25)
plt.xlim([-1.5, 1.5])
plt.ylim([-1.5, 1.5])
plt.savefig(file)
ct = ct+1
print(file)
The graph below shows the change in angular displacement and angular velocity with respect to time, where both of the curves reduces the amplitude because of the damp factor.

The animation illustrating the pendulum motion is shown below.