Week 3 - Solving second order ODEs
Aim: To solve 2nd order governing ordinary differential equation of a motion of a simple pendulum using Python.
Theory:
A pendulum is nothing, but mass or weight suspended at fixed point (pivot point) by using string of foxed length. If there is no action of external force on pendulum, it remains in equilibrium position. But when it is displaced from its equilibrium position with the application of force, it oscillates at its mean position due to gravity. The time taken to complete one oscillation from left swing to right swing or from right swing to left swing is called as period of pendulum. Period of pendulum is given by,
`T = 2 π √ ( L/ g )`
Where L, is length of the string of pendulum and g is acceleration due to gravity.
Simple pendulum is a type of pendulum in which a mass (bob) is attached at the end of massless string. String is fixed at pivot which is frictionless. Simple pendulum is shown in figure below.

Figure: Simple pendulum
Governing differential equation which describes the motion of pendululm is given by,

Where,
g = gravity in m/s^2,
L = length of the pendulum in m,
m = mass of the ball in kg,
b=damping coefficient.
Above equation is solved using python code as shown below,
Python code
# To solve 2nd order ODE using Python
import numpy as np
from scipy.integrate import odeint
import math
import matplotlib.pyplot as plt
#funcion that returns dtheta/dt
def function(theta,t,b,g,l,m):
theta1 = theta[0]
theta2 = theta[l]
dtheta1_dt = theta2
dtheta2_dt = -(b/m)*theta2-(g/l)*math.sin(theta1)
dtheta_dt = [dtheta1_dt,dtheta2_dt]
return dtheta_dt
b=0.05
g=9.81
l=1
m=1
#Initial conditions
theta_0 = [0,3]
# Input for time
t = np.linspace(0,20,200)
theta = odeint(function,theta_0,t,args=(b,g,l,m))
#plot result
plt.plot(t,theta[:,0],'g-',label = r'$\frac{d\theta_1}{dt}=\theta2$')
plt.plot(t,theta[:,1],'b--',label=r'$\frac{d\theta2}{dt}=-\frac{b}{m}\theta_2-\frac{g}{l}sin\theta_1$')
plt.xlabel('Plot')
plt.ylabel('Time')
plt.legend()
plt.savefig('output.png')
plt.show()
# To creat animation
ct = 1
x0 = 0
y0 = 0
for i in theta[:,0]:
x1=x0+(l*math.sin(i))
y1=y0+(-l*math.cos(i))
filename = str(ct)+'.png'
ct = ct +1
plt.figure()
plt.plot([-1,1],[0,0],"black")
plt.plot([x0,x1],[y0,y1],"red")
plt.plot(x1,y1,'o',markersize = '20')
plt.xlim([-1.5,1.5])
plt.ylim([-1.5,1.0])
plt.savefig(filename)
Results:

Animation:
Conclusion
Governing differential equation of simple pendulum is solved using Python program. Animation is working correctly. Hence it can be concluded that solution obtained by program is correct.