Week 3 - Solving second order ODEs
A simple pendulum can be described as a device where its point mass is attached to a light inextensible string and suspended from a fixed support. The vertical line passing through the fixed support is the mean position of a simple pendulum.
The coding for the simple pendulum model is :
import numpy as np
from scipy.integrate import odeint
import math
import matplotlib.pyplot as plt
#function that returns dz/dt
def model(theta,t,b,g,l,m):
theta1 = theta[0]
theta2 = theta[1]
dtheta1_dt = theta2
dtheta2_dt = -(b/m)*theta2 - (g/l)*math.sin(theta1)
dtheta_dt = [dtheta1_dt, dtheta2_dt]
return dtheta_dt
# input
b = 0.05
g = 9.81
l = 1
m = 1
# initial condition
theta_0 = [0,3]
# time points
t = np.linspace(0,20,200)
# solve ODE
theta = odeint(model,theta_0,t,args = (b,g,l,m))
# ploting results
plt.plot(t,theta[:,0],'b-',label=r'$\frac{d/theta_1}{dt}=\theta2$')
plt.plot(t,theta[:,1],'r--',label=r'$\frac{d/theta_2}{dt}= -\frac{b}{m}\theta_2-\frac{g}{L}sin\theta_1$')
plt.xlabel('time')
plt.ylabel('plot')
plt.legend(loc='best')
plt.show()
# making animation
THETA3 = []
for theta3 in theta[:,0]:
THETA3.append(theta3)
ct = 1
x0 = 0
y0 = 0
for THETA4 in THETA3:
x1 = l*math.sin(THETA4)
y1 = -l*math.cos(THETA4)
filename= str(ct) +'.png'
ct = ct+1
plt.figure()
plt.plot([-1.5,1.5],[0,0],linewidth=8)
plt.plot([x0,x1],[y0,y1],linewidth=3)
plt.plot(x1,y1,'o',markersize = 15)
plt.xlim([-1.5,1.5])
plt.ylim([-1.5,1])
plt.savefig(filename)
THE OUTPUT GRAPH WE WILL GET IS:

EXPLANATION OF CODING :
- To solve ode,import odeint module from scipy module.
- Breake down the second order ODE into two first order ODE,the first ode will give the values of displacement and second ODE will give the values of velocity.
- Define the initial condition to solve ODE as tetha_0=[0,3]
- To obtain smooth motion,divide time point between 0 to 20 sec using linspace command.
- To solve ODE use 'ODEINT' and save values in variable 'tetha'
tetha=odeint(model,tetha_0,t,args=(b,g,l,m))
6. First coloumn of matrix represents the values of displacement hence extract values of displacement and add it in null matrix TETHA3 using append command
7. To show the motion of pendulum for every value of TETHA3 extract values of THETHA4 using loop.
THE YOUTUBE LINK FOR THE WORKING MODEL OF SIMBLE PENDULUM IS :https://youtu.be/P3ADt9VEzG4