Solving second order ODEs
AIM
To write a code and execute the simulation of simple pendulum usind second order equation and create a animation using python.
In the above equation,
g = gravity in m/s2,
L = length of the pendulum in m,
m = mass of the ball in kg,
b=damping coefficient.
L=1 metre,
m=1 kg,
b=0.05.
g=9.81 m/s2.
Simulate the motion between 0-20 sec, for angular displacement=0,angular velocity=3 rad/sec at time t=0.
import math
import matplotlib.pyplot as plt
import numpy as np
import scipy
from scipy.integrate import odeint
#Defining Function that return 'dtheta_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
#Inputs
b = 0.05
g = 9.81
l = 1.0
m = 1.0
#Initial condition
theta_0 = [0,3]
t = np.linspace(0,20,250)
theta = odeint(model,theta_0,t,args = (b,g,l,m))
#Plot results
plt.plot(t,theta[:,0], 'g', label=r'displacement')
plt.plot(t,theta[:,1], 'b', label=r'velocity')
plt.xlim([0,20])
plt.ylim([-3,3])
plt.legend(loc='best')
plt.xlabel('time')
plt.ylabel('Plot')
plt.savefig('output.png')
plt.show()
#Animation of the pendulum
ct = 1
for theta in theta[:,0]:
x0 = 0
y0 = 0
x1 = l*math.sin(theta)
y1 = -l*math.cos(theta)
plt.figure()
plt.plot([-0.25,0.25],[0,0], "blue", linewidth=5)
plt.plot([x0,x1],[y0,y1],"red")
plt.plot(x1,y1,'o', markersize=15)
plt.xlim([-1,1])
plt.ylim([-1.5,1])
filename = str(ct) + '.png'
plt.savefig(filename)
EXPLANATION OF CODE
- create a new file and import math, mathplotlib,scipy and numpy
- define a function module which have the inputs b,g,l,m , theta, t and return dtheta_dt
- defina initial parameters
- solve the differntial equation using the odeint which is imported from scipy.integrate
- theta is solution ODE containing two column vector
- first is angular displacement and second is angular velocity.
- plot the angular displacement and velocity against the time.
- to create animation of simple pendulum set the plots for different angular displacement
- save the figure and create gif file.
RESULTS AND ANIMATION

