Challenge

Week 3 - Solving second order ODEs

Aim : To solve an ode using python that represents the equation of motion of a simple pendulum with damping and create an animation to show the movement of the pendulum acoording to the funtion given.

Theory : The given Ode is a second order differential equation, that represents the motion of a simple pendulum.

where

b = damping coefficient

m = mass of the bob

g = acceleration due to gravity

L = length of string

Solution :

Firstly, we converted the 2nd order differential equation to a lower order differential equation using some assumptions in the 2nd order ode.

Code :

import numpy as np 
from scipy.integrate import odeint
import matplotlib.pyplot as plt 
import math

def ode_func(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

b=0.05     #damping coefficient
g=9.81     #acceleration due to gravity
l=1        #length of string
m=1	       #mass of the sphere

#initial conditions
theta_0 = [math.pi/2,0]

#time points
t=np.linspace(0,20,150)   #the simulation is taken under the time interval of 0-20

#solve ode
theta = odeint(ode_func,theta_0,t,args = (b,g,l,m))    #odeint is used to solve the ode

#plot 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\theta2}{dt}=-\frac{b}{m}\theta_2-\frac{g}{L}sin\theta_1$')
plt.ylabel('Plot')
plt.xlabel('Time')
plt.legend(loc='best')
plt.show()

ct=1

#for animation 
for t in theta[:,0]:
	x0=0
	y0=0
	x1=(1*math.sin(t))
	y1=-(1*math.cos(t))
	filename = str(ct)+'.png'
	ct = ct+1

	#plotting as done for forward kinematics
	plt.figure()
	plt.plot([-0.5,0.5],[0,0],'black',linewidth = 5)  #baseline
	plt.plot([x0,x1],[y0,y1],linewidth = 3, color = 'r')
	plt.plot(x0,y0,'o',markersize=5)
	plt.plot(x1,y1,'o',markersize = 20, color = 'blue')
	plt.xlim([-1.5,1.5])
	plt.ylim([-1.5,1.5])
	plt.savefig(filename)


Result :

Graph that shows damping in the pendulum

Animation:

In the given animation we can see the depletion of the amplitude of the pendulum, this shows the damping effect on the pendulum.

Your portfolio, next

Ship work like this
in your own course.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.