Challenge

Week 3 - Solving second order ODEs

Aim: To solve second order ODE and use the calculated information to animate the motion of the pendulum using PYTHON.

Objective :

  • By using ode solver which is imported from scipy module. The ode should require a simple differential equation to solve any kind of higher-order differential equation.

Python Code:

"""
Second Order ODE
"""
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import math

#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

#inputs
b=0.05
g=9.81
l=1
m=1

#Intial conditions
theta_0=[0,3]

#Time
t=np.linspace(0,20,100)

#Solve ODE

theta=odeint(model,theta_0,t,args=(b,g,l,m))

#Plot
plt.plot(t,theta[:,0],'b-',label=r'$\frac{d\theta1}{dt}=\theta2$')
plt.plot(t,theta[:,1],'r--',label=r'$\frac{d\theta2}{dt}=-\frac{b}{m}\theta2-\frac{g}{l}sin\theta1$')
plt.xlabel('time')
plt.ylabel('plot')
plt.legend(loc='best')
plt.show()

#Animation
ct=1

x0=0 
y0=0

for i in theta[:,0]:
	x1=(1*math.sin(i))
	y1=(-1*math.cos(i))

	filename='pendulum%05d.png'%ct
	ct=ct+1

	plt.figure()
	plt.plot([-1,1],[0,0],"black",linewidth=10)
	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)

Code Explanation:

  • Import module numpy as np, to solve ode import odeint module from scipy module.
  • Define function and break down the second-order ode into two first-order ode, the first ODE will give the values of angular displacement and the second will give the values of angular velocity.
  • Initialize the input values of b,g,m,l.
  • Define the initial condition to ODE as theta_0=[0,3]
  • To obtain smooth motion divide time point between 0 to 20 using np.linspace command.
  • To solve ODE use 'odeint' and save values in theta.
  • Plotting the result using plt.plot command.
  • Using for loop for animation.
  • Name the file and number of unstitched images are formed.
  • These images are stitched using image magick and are made into an animation.

Plot:

Animation of the pendulum:

https://youtu.be/18qJGjj1wEc

Conclusion:

  • We have animated the simple pendulum using ODE solver
  • With the use of PYTHON to study the motion of simple pendulum can be studied with the help of animation and plots. Similarly, we can solve other higher-order differential equations and their solutions and plots can be obtained easily
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.