Challenge

Week 3 - Solving second order ODEs

Aim:- To solve the second-order ode function by using Python and shows the motion of the pendulum

Objective:-

1. Writing a program that solves the following ODE

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.

2. Writing a program in Python that will simulate the pendulum motion

using,

L=1 metre,

m=1 kg,

b=0.05.

g=9.81 m/s2.

Initial conditions for simulating the motion

t= 0 to 20 sec (time)

Angular displacement=0,

Angular velocity=3 rad/sec at time t=0.

Theory:- In engineering, ODE is used to describe the transient behavior of a system. A simple example is a pendulum. The way the pendulum moves depends on the Newtons second law. When this law is written down, we get a second order Ordinary Differential Equation that describes the position of the "ball" w.r.t time.

The ordinary differential equation helps us to solve the many engineering systems such as harmonic, vibrations, damping, etc. A pendulum consists of a mass "m" hanging from a string of length ''l'' with fixed point. when pendulum released,it swings to and fro motion with angular velocity=3 rad/sec at time t=0.

Program:-

# To solve the 2nd order ODE using python
import numpy as np
from scipy.integrate import odeint
import math
import matplotlib.pyplot as plt

# function that returns dtheta/dt
# User defined 
def 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

# Main program	
# Given data
# Damping coefficient
b = 0.05
# Gravity(m/s2)
g = 9.81
# Length of pendulum string (m)
l = 1
# Mass of pendulum(kg)
m = 1

# Initail condition
theta_0 = [0,3]

# Input for time
t = np.linspace(0,20,150)

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

# Plot result
plt.plot(t,theta[:,0],'g-',label = 'Angular displacement(θ)')
plt.plot(t,theta[:,1],'b--',label = 'Angular velocity(dθ/dt)')
plt.xlabel('Plot')
plt.ylabel('Time')
plt.legend()
plt.show()

# To create 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])
	#saving images
	plt.savefig(filename)

print(ct)

Output:-

Animation:-

Conclusion:- Solving second order ODE problem with example of simple pendulum by using python and results found satisfactory

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.