Challenge

Week 3 - Solving second order ODEs

AIM:

Write a program in Matlab that will simulate the pendulum motion.

  • Calculate the angular displacement and angular velocity.
  • Animation of the simple pendulum oscillation.

ODE for simple pendulum,

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.

SIMPLE PENDULUM DIAGRAM: -

ODE DERIVATION: -

use,

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.

PROGRAM

"""Solving Second order differeential equation using python
"""
#solution
import math
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint

#Second order diffrential equation in a first order ode
#function that return dtheta/dt


def model(theta,t,b,g,l,m):
theta_1 = theta[0]
theta_2 = theta[1]
dtheta1_dt = theta_2
dtheta2_dt = -(b/m)*theta_2-(g/l)*math.sin(theta_1)
dtheta = [dtheta1_dt,dtheta2_dt]
return dtheta

#*****paramater*****
b = 0.05
g = 9.81
l = 1
m = 1

#intial condition
theta_0 = [0,3]

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

#slove ode
theta = odeint(model,theta_0,t,args = (b,g,l,m))
#plot results
plt.plot(t,theta[:,0],label = r'$({dtheta_1}/{dt}) = theta2$')
plt.plot(t,theta[:,1],label = r'$({dtheta_2}/{dt}) = -(({b/m})theta2)-({g/l})(sin(theta_1))$')
plt.xlabel('time')
plt.ylabel('displacement & velocity')
plt.legend(loc='best')
plt.show()

#Animation

ct = 1
for i in range(len(theta)):
x0 = 0
y0 = 0
x1 = math.sin(theta[i,0])
y1 = -math.cos(theta[i,0])

ct = ct+1

filename = str(ct) + '.png'

plt.figure()
cord = plt.plot([x0,x1],[y0,y1],color = 'k', lw = 2)
bob = plt.plot(x1,y1,'o',markersize = 15, color = 'r')
plt.xlim(-1,1)
plt.ylim(-2,0)
plt.savefig(filename)

Explaination:

1)Import the math function

2)Import numpy for array

3)Import the plot

4)Use odeint for intergration.

5)Time values created using linspace

6)To provide the input condition

7)Initialize new function and use return command to return function value as T

8)To intergration of all the value

9)Using plot command to plot the graph

Plot Result:-

Plotting a graph when time is change then displacement and velocity also very.

Conclusion:-

Here second order diffrential equation is solved using python.

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.