Week 3 - Solving second order ODEs
AIM:
To simulate the transient behaviour of a simple pendulum using Python.
OBJECTIVES:
- To write a program that solves the second order ODE which represents the equation of motion of a simple pendulum with damping.
- To simulate the motion of the simple pendulum with damping & creating an animation.
Program:
# Program for solving second order ODE
import matplotlib.pyplot as plt
import math
import numpy as np
from scipy.integrate import odeint
def ode_function(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
# damping coefficient
b = 0.05
# acceleration due to gravity(m/s^2)
g = 9.81
# length of string (m)
l = 1
# mass of bob (kg)
m = 1
# Initial Conditions
theta_0 = [0,3]
# time points
t_span = np.linspace(0,20,100)
# Solving ODE
theta = odeint(ode_function,theta_0,t_span,args = (b,g,l,m))
# Plotting the graph
plt.plot(t_span,theta[:,0])
plt.plot(t_span,theta[:,1])
plt.xlabel('Time (second)')
plt.ylabel('Plot')
plt.title('Damped Harmonic motion of a Simple Pendulum')
plt.ylim([-4,4])
plt.xlim([0,20])
plt.grid()
plt.show()
# for loop to create animation of motion of pendulum
ct =1
range = theta[:,0]
for i in range:
x_start = 0
y_start = 0
x_end = l*math.sin(i)
y_end = -l*math.cos(i)
# Plotting for animation
plt.figure()
# Plotting the rigid support through which string of pendulum is attached
plt.plot([-0.5,0.5],[0,0],linewidth=3,color='b')
# Plotting String of pendulum
plt.plot([x_start,x_end],[y_start,y_end],linewidth=3)
# Plotting Bob of pendulum
plt.plot(x_end,y_end,'o',markersize=15,color='r')
plt.xlim([-1.5,1.5])
plt.ylim([-1.5,0.5])
plt.title('Transient behaviour of a Simple Pendulum')
filename = 'test%05d.png' % ct
plt.savefig(filename)
ct = ct + 1
Explanation:
- Firstly, import all the modules required.
- Define the function as it will be used to solve repeatedly & provide the inputs.
- Run the program & check whether it has error or not.
- If errors come read the error & try to debug it.
- Check whether graph & images obtained are proper or not.
- Convert the images into animation.
Errors encountered:
Module error.
Name error.
syntax error.
Result:

https://drive.google.com/file/d/1BYKKEHlm6AJMOznASKbDUxXrJDgkNp8S/view?usp=share_link
Conclusion:
Python Program for ODE is done & output is shown.