Anniversary Scholarship 2025: up to ₹79,000 | 6 Guaranteed Job Interviews | Limited to 100 Seats. Apply Now

00D 00H 00M 00S

Menu

Executive Programs

Workshops

Projects

Blogs

Careers

Placements

Student Reviews


For Business


More

Academic Training

Informative Articles

Find Jobs

We are Hiring!


All Courses

Choose a category

Mechanical

Electrical

Civil

Computer Science

Electronics

Offline Program

All Courses

All Courses

logo

CHOOSE A CATEGORY

Mechanical

Electrical

Civil

Computer Science

Electronics

Offline Program

Top Job Leading Courses

Automotive

CFD

FEA

Design

MBD

Med Tech

Courses by Software

Design

Solver

Automation

Vehicle Dynamics

CFD Solver

Preprocessor

Courses by Semester

First Year

Second Year

Third Year

Fourth Year

Courses by Domain

Automotive

CFD

Design

FEA

Tool-focused Courses

Design

Solver

Automation

Preprocessor

CFD Solver

Vehicle Dynamics

Machine learning

Machine Learning and AI

POPULAR COURSES

coursePost Graduate Program in Hybrid Electric Vehicle Design and Analysis
coursePost Graduate Program in Computational Fluid Dynamics
coursePost Graduate Program in CAD
coursePost Graduate Program in CAE
coursePost Graduate Program in Manufacturing Design
coursePost Graduate Program in Computational Design and Pre-processing
coursePost Graduate Program in Complete Passenger Car Design & Product Development
Executive Programs
Workshops
For Business

Success Stories

Placements

Student Reviews

More

Projects

Blogs

Academic Training

Find Jobs

Informative Articles

We're Hiring!

phone+91 9342691281Log in
  1. Home/
  2. Giridhar Lingutla/
  3. Solving second order Ordinary Differential Equations (ODEs) of a Simple Pendulum using Python

Solving second order Ordinary Differential Equations (ODEs) of a Simple Pendulum using Python

Objective: Write a program to solve an ODE which represents the equation of motion of a simple pendulum with damping and animate a simple pendulum in motion.   Simple Pendulum: A simple pendulum consists of a ball (point-mass) m hanging from a (massless) string of length L and fixed at a pivot…

    • Giridhar Lingutla

      updated on 24 Feb 2021

    Objective:

    Write a program to solve an ODE which represents the equation of motion of a simple pendulum with damping and animate a simple pendulum in motion.

     

    Simple Pendulum:

    A simple pendulum consists of a ball (point-mass) m hanging from a (massless) string of length L and fixed at a pivot point P. When displaced to an initial angle and released, the pendulum will swing back and forth with periodic motion. By applying Newton's secont law for rotational systems, the equation of motion for the pendulum may be obtained

    τ=Iα=-mgsinθL=mL2d2θdtτ=Iα=−mgsinθL=mL2d2θdt

    and rearranged as

    d2θdt2+gLsinθ=0d2θdt2+gLsinθ=0

    and if a damper is introduced in the system the above equation becomes

    d2θdt2+bmdθdt+gLsinθ=0d2θdt2+bmdθdt+gLsinθ=0

    In the above equation,

    g = gravity in m/s^2,

    L = length of the pendulum in m,

    m = mass of the ball in kg,

    b=damping coefficient.

    Governing Equations:

    To solve the above equation in Python, we need to transform the given second order ODE into first order ODE:

    suppose Î¸=θ1θ=θ1

    dθdt=dθ1dt=θ2dθdt=dθ1dt=θ2    .(I)

    d2θdt2=d2θ1dt2=ddt(dθ1dt)=ddt(θ2)d2θdt2=d2θ1dt2=ddt(dθ1dt)=ddt(θ2)     .(II)

    ODE: d2θdt2+bmdθdt+gLsinθ=0d2θdt2+bmdθdt+gLsinθ=0

    Replacing Î¸withθ1θwithθ1

    d2θ1dt2+bmdθ1dt+gLsinθ1=0d2θ1dt2+bmdθ1dt+gLsinθ1=0

    by replacing the values with equation II

    dθ2dt+bmθ2+gLsinθ1=0dθ2dt+bmθ2+gLsinθ1=0

    dθ2dt=-bmθ2-gLsinθ1dθ2dt=−bmθ2−gLsinθ1

    so we get two first order ODE's, dθ1dt=θ2dθ1dt=θ2,dθ2dt=-bmθ2-gLsinθ1dθ2dt=−bmθ2−gLsinθ1

     

    Python Code:

    """
    Simple Pendulum animation and ODE solution by Giridhar
    """
    import math
    import matplotlib.pyplot as plt
    import numpy as np
    from scipy.integrate import odeint
    
    # 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 
    # damping coefficient
    b = 0.05
    # gravity(m/s^2)
    g = 9.81  
    # length of the pendulum (m)                                                               
    l = 1  
    # mass of ball (kg)                                                                  
    m = 1      
    
    # Initial Conditions
    theta_0 = [0,3] 
    
    # time points
    t = np.linspace(0,20,150)
    
    # ode solution
    theta = odeint(model,theta_0,t,args = (b,g,l,m))
    
    # plotting the results
    plt.plot(t,theta[:,0],'b-',Label = r'$frac{dtheta1}{dt}=theta2$(Displacement)')
    plt.plot(t,theta[:,1],'r--',Label = r'$frac{dtheta2}{dt}=-frac{b}{m}theta2-frac{g}{l}sintheta1$(Velocity)')
    plt.xlabel('Time (s)')
    plt.ylabel('Plot')
    plt.title('Harmonic motion of a Pendulum_Damped')
    plt.legend(loc='best')
    plt.savefig('Pendulum_Damped')
    plt.show()
    
    # Animation of Pendulum motion 
    
    ct =1
    tmp = theta[:,0]
    for i in tmp:
    	x_start = 0                                                           
    	y_start = 0
    	x_end =  l*math.sin(i)                                          
    	y_end = -l*math.cos(i)
    
    	filename = str(ct) + '.png'
    	ct = ct + 1
    	
    	plt.figure()
    	# string
    	plt.plot([x_start,x_end],[y_start,y_end],linewidth=3)
    	# pendulum ball
    	plt.plot(x_end,y_end,'o',markersize=15,color='y')
    	# support
    	plt.plot([-1.25,1.25],[0,0],linewidth=5,color='k')
    	plt.plot([0,0],[0,-1.5],'--',color='r')
    	plt.xlim([-1.25,1.25])
    	plt.ylim([-1.5,1.5])
    	plt.title('Animation of a Pendulum')
    	plt.savefig(filename)

     

    Plot:

    The above plot of angular displacement and angular velocity shows the pendulum's motion to be gradually decreasing. This is due to the damping effect which decreases the amplitude and the velocity of motion.

    Pendulum Motion Animation:

    Errors:

    • The first 2 errors are related to version 3.3 and did not cause any trouble to coding and output.
    • The third error is regarding the number of figures saved. As there are 150 figures generated, the software is warning about consuming too much memory to create the same.  

     

    Python Code Explanation:

    • Math module is imported as the code contains mathematical calculations.
    • matplotlib.pyplot as plt is imported as we need plots from the calculations performed.
    • numpy is imported for arrays.
    • odeint is imported from scipy.integrate for solving ODE.
    • A function is defined with undefined variables of theta1 and theta 2 and will be defined outside of the function.
    • The value of dtheta_dt is returned back to the function.
    • Inputs such as b,g,l,m are provided according to function.
    • An array of theta was created to define Angular displacement and Angular velocity.
    • An array of a time points was created to store 150 equally spaced intervals between 0 to 20 seconds.
    • The function is called to solve ODE and odeint command is used as a prefix.
    • plt.plot command is used to plot the graph of variation of angular displacement and angular velocity wrt time.
    • plt._label is used for assingning lables to the graph, plt.title is used for the title of the graph.
    • The plot is saved using plt.savefig command and shown using plt.show command.

    Simple Pendulum Animation:

    • ct=1 is assigned before for loop and ct= ct+1 inside the loop, so that each figure is saved with the name starting with 1 and incremented by 1.
    • A for loop is used to give the values of angular position and is stored in tmp and iterated.
    • plt.plot is used to plot string, ball, the center line (axis) and support etc required for animation.
    • plt._lim command is used to define limits in coordinates for the whole graph.
    • The plot is saved using plt.savefig command.
    • These .png files are converted into a gif file using the imgflip.com. We can also do it using the cygwin and imagemagick softwares together. 

    Conclusion: 

    A program in Python is created and succesfully executed to solve Ordinary Differential Equations of a damped pendulum and animated a simple pendulum in motion.

    Leave a comment

    Thanks for choosing to leave a comment. Please keep in mind that all the comments are moderated as per our comment policy, and your email will not be published for privacy reasons. Please leave a personal & meaningful conversation.

    Please  login to add a comment

    Other comments...

    No comments yet!
    Be the first to add a comment

    Read more Projects by Giridhar Lingutla (60)

    Week 6 - Data analysis

    Objective:

    https://skill-lync.com/projects/data-analysis-using-python-48

    calendar

    02 Mar 2021 07:35 PM IST

      Read more

      Data Analysis using Python

      Objective:

      Objective: Extract a plot between any two quantities from the given data file automatically. Compatibility check: Code should exit gracefully, if a non-compatible file is provided as an input. Calculate the area under P-V diagram. Calculate the power output of an engine running at 1500 RPM. Calculate the specific fuel…

      calendar

      02 Mar 2021 07:35 PM IST

        Read more

        Curve Fitting using Python

        Objective:

        Objective: Write a Python Program to curve fit a linear and cubic polynomial for the given Cp data and explain the results.   Curve Fitting: Curve fitting is the process of constructing a curve, or mathematical function, that has the best fit to a series of data points, possibly subject to…

        calendar

        01 Mar 2021 12:41 PM IST

          Read more

          Find Minimum Cushion Pressure with Newton-Raphson method of an Air Cushion Vehicle to break Ice in Python

          Objective:

          Objective: Write a Python program to find minimum cushion pressure of an Air Cushion Vehicle to Break Ice with Newton-Raphson method.   Governing Equation: The factors involved are: p - cushion pressure h - thickness of the ice field r - size of the air cushion σ - tensile strength of the ice  β -…

          calendar

          27 Feb 2021 05:20 PM IST

            Read more

            Schedule a counselling session

            Please enter your name
            Please enter a valid email
            Please enter a valid number

            Related Courses

            coursecard

            Design loads considered on bridges

            Recently launched

            10 Hours of Content

            coursecard

            Design of Steel Superstructure in Bridges

            Recently launched

            16 Hours of Content

            coursecard

            Design for Manufacturability (DFM)

            Recently launched

            11 Hours of Content

            coursecard

            CATIA for Medical Product Design

            Recently launched

            5 Hours of Content

            coursecardcoursetype

            Accelerated Career Program in Embedded Systems (On-Campus) Courseware Partner: IT-ITes SSC nasscom

            Recently launched

            0 Hours of Content

            Schedule a counselling session

            Please enter your name
            Please enter a valid email
            Please enter a valid number

            logo

            Skill-Lync offers industry relevant advanced engineering courses for engineering students by partnering with industry experts.

            https://d27yxarlh48w6q.cloudfront.net/web/v1/images/facebook.svghttps://d27yxarlh48w6q.cloudfront.net/web/v1/images/insta.svghttps://d27yxarlh48w6q.cloudfront.net/web/v1/images/twitter.svghttps://d27yxarlh48w6q.cloudfront.net/web/v1/images/youtube.svghttps://d27yxarlh48w6q.cloudfront.net/web/v1/images/linkedin.svg

            Our Company

            News & EventsBlogCareersGrievance RedressalSkill-Lync ReviewsTermsPrivacy PolicyBecome an Affiliate
            map
            EpowerX Learning Technologies Pvt Ltd.
            4th Floor, BLOCK-B, Velachery - Tambaram Main Rd, Ram Nagar South, Madipakkam, Chennai, Tamil Nadu 600042.
            mail
            info@skill-lync.com
            mail
            ITgrievance@skill-lync.com

            Top Individual Courses

            Computational Combustion Using Python and CanteraIntroduction to Physical Modeling using SimscapeIntroduction to Structural Analysis using ANSYS WorkbenchIntroduction to Structural Analysis using ANSYS Workbench

            Top PG Programs

            Post Graduate Program in Hybrid Electric Vehicle Design and AnalysisPost Graduate Program in Computational Fluid DynamicsPost Graduate Program in CADPost Graduate Program in Electric Vehicle Design & Development

            Skill-Lync Plus

            Executive Program in Electric Vehicle Embedded SoftwareExecutive Program in Electric Vehicle DesignExecutive Program in Cybersecurity

            Trending Blogs

            How to Learn CAD Design: Step-by-Step GuideGD&T Basics: How to Read and Apply GD&T Symbols SolidWorks vs Creo: Best CAD Software to Learn for Mechanical Engineers Engineering Edtech in India: Busting Myths & Building Careers How to Get a Core Mechanical Engineering Job After Graduation

            © 2025 Skill-Lync Inc. All Rights Reserved.

                        Do You Want To Showcase Your Technical Skills?
                        Sign-Up for our projects.