oscar nieves (11710858) computational physics project - inverted pendulum

52
1 Numerical simulation of the nonlinear dynamics of an inverted pendulum system in MATLAB Oscar A. Nieves (11710858) School of Physics and Advanced Materials, University of Technology, Sydney, 15 Broadway, Ultimo, New South Wales 2007, Australia E-mail: [email protected] Date: 10/06/2016 Abstract: the aim of this project is to produce a suitable numerical simulation for an inverted pendulum attached to a cart that can only move horizontally. Forces are introduced to the system in the form of air drag and friction, which cause the system to lose energy quite rapidly. These forces can be adjusted by defining the respective values of the damping constants. Other parameters that can be varied will include the pendulum’s and cart’s masses, the length of the pendulum and the initial angular displacement and velocity of the pendulum with respect to the cart. An analysis of the dynamic and chaotic behaviour of the system is performed using MATLAB and implementing a 4 th order Runge-Kutta algorithm. The computer program also possesses a built-in animation of the system that is self-adjusting to any initial conditions or parameters imposed by the user. The program can also be easily adjusted by introducing new forces and writing the respective 1 st order differential equations that correspond to the new system. As expected, very small variations in the initial conditions cause dramatic effects on the system’s motion, and the chaotic behaviour is portrayed to a reasonable accuracy by the RK4 algorithm. Nomenclature mass of the pendulum (in kg) length of the rod (in metres) mass of the cart (in kg) time (in seconds) angular displacement of the pendulum (in radians) ̇ angular velocity of the pendulum (in rad/s) ̈ angular acceleration of the pendulum (in rad/s 2 ) horizontal displacement of the cart (in metres) ̇ horizontal velocity of the cart (in m/s) ̈ horizontal acceleration of the cart (in m/s 2 ) damping force on pendulum due to air drag (in N) damping force on cart due to friction with rails (in N) damping coefficient of air drag (in N.s/m) damping coefficient of friction (in N.s/m) 1. Aim and Motivation Nonlinear dynamics are the governing body in the physical universe. They define the tendency of systems to behave very differently under minor changes in their initial conditions. Chaos theory has been built around the more extreme end, showing how systems can become

Upload: oscar-nieves

Post on 22-Jan-2018

244 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

1

Numerical simulation of the nonlinear dynamics of an inverted

pendulum system in MATLAB

Oscar A. Nieves (11710858)

School of Physics and Advanced Materials, University of Technology, Sydney, 15 Broadway,

Ultimo, New South Wales 2007, Australia

E-mail: [email protected]

Date: 10/06/2016

Abstract: the aim of this project is to produce a suitable numerical simulation for an inverted

pendulum attached to a cart that can only move horizontally. Forces are introduced to the

system in the form of air drag and friction, which cause the system to lose energy quite

rapidly. These forces can be adjusted by defining the respective values of the damping

constants. Other parameters that can be varied will include the pendulum’s and cart’s masses,

the length of the pendulum and the initial angular displacement and velocity of the pendulum

with respect to the cart. An analysis of the dynamic and chaotic behaviour of the system is

performed using MATLAB and implementing a 4th order Runge-Kutta algorithm. The

computer program also possesses a built-in animation of the system that is self-adjusting to

any initial conditions or parameters imposed by the user. The program can also be easily

adjusted by introducing new forces and writing the respective 1st order differential equations

that correspond to the new system. As expected, very small variations in the initial conditions

cause dramatic effects on the system’s motion, and the chaotic behaviour is portrayed to a

reasonable accuracy by the RK4 algorithm.

Nomenclature

𝑚 mass of the pendulum (in kg)

𝐿 length of the rod (in metres)

𝑀 mass of the cart (in kg)

𝑡 time (in seconds)

𝜃 angular displacement of the pendulum (in radians)

�̇� angular velocity of the pendulum (in rad/s)

�̈� angular acceleration of the pendulum (in rad/s2)

𝑋 horizontal displacement of the cart (in metres)

�̇� horizontal velocity of the cart (in m/s)

�̈� horizontal acceleration of the cart (in m/s2)

𝐷 damping force on pendulum due to air drag (in N)

𝐹 damping force on cart due to friction with rails (in N)

𝜇𝐷 damping coefficient of air drag (in N.s/m)

𝜇𝐹 damping coefficient of friction (in N.s/m)

1. Aim and Motivation

Nonlinear dynamics are the governing body in the physical universe. They define the tendency

of systems to behave very differently under minor changes in their initial conditions. Chaos

theory has been built around the more extreme end, showing how systems can become

Page 2: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

2

unpredictable given a sufficient complexity in the degrees of freedom and parameters that make

up the system. However, they are seldom studied in undergraduate physics courses around the

world and are often left to the mathematicians to deal with the real aspects of real systems that

are, in fact, non-deterministic and often unpredictable. Furthermore, nonlinear dynamics are

often quite difficult to model using computational models due to the absence of analytical

solutions with which the numerical approximations can be compared.

Several built-in MATLAB functions allow for solving differential equations numerically in a

very efficient way, often in one-line commands. Functions like ODE45 allow for the

implementation of a 4th order Runge-Kutta algorithm to solve a differential equation of any

order numerically, with a high degree of accuracy as the number of steps increases. However,

functions like this one are limited to solving one differential equation at a time, and as is the

case with multi-body systems in physics, other methods need to be investigated. A two-body

system as the inverted pendulum, for example, has two second order differential equations that

are coupled in terms of their second derivatives. This makes it particularly challenging for

MATLAB to solve as functions need to be declared before they are called in a statement or

another function. In this paper, the equations of motion needed to be uncoupled before they

could be fed into the program.

The aim of this project is then to provide not only a simulation of an inverted pendulum system,

but also a program that can solve any system of two second order differential equations using

the RK4 algorithm. Apart from this, the documentation hereby presents a detailed step by step

method (see Appendix A and B) on how to adapt the RK4 algorithm to any system of multiple

differential equations, which has been identified as a gap in the literature related to numerical

analysis. It is in the hope of the author that this method can be improved in the future and serves

as a foundational platform for solving more complex physical systems, and that undergraduate

science and engineering students alike can learn to understand the links between numerical

algorithms and programming, and how these can provide a different and quite useful

perspective on problem-solving techniques.

2. Introduction

The inverted pendulum is a commonly studied problem in engineering and control theory, as

it is a simple two-body system that exhibits chaotic behaviour. Most studies that have been

done on the system usually involve programming a PID controller on the cart that is connected

to a sensor which measures the angle of the pendulum with respect to the vertical axis about

the pivot point. The controller then uses a transfer function to generate a frequency-domain

response to the motion of the pendulum, hence compensating for its falling motion and

maintaining it upright regardless of disturbances. However, not many studies have been

performed on the full-dynamics of the system, as this control theory approach is limited to very

small angles and uses state space equations and matrices.

The approach taken in this paper is different to that found in control theory. It focuses on the

nonlinear dynamics of the inverted pendulum and cart and analyses it using a 4th order Runge-

Kutta (RK4) numerical algorithm to solve for the equations of motion. The MATLAB program

solves these equations and uses the information to generate an simple animation that shows

how the pendulum and cart move together given different initial conditions, such as the mass

of the bob and the cart, the length of the pendulum, initial position and velocity; and also the

effect of air drag and friction on the system.

Page 3: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

3

Although this is a simple system, it reveals useful information about the nonlinear behaviour

of real systems found in nature. It is found through the simulation that small changes in initial

conditions produce reasonably different results. Furthermore, the program can be easily

modified to solve any other two-body system by changing the initial conditions and differential

equations, including linear and nonlinear ones.

The main challenge with nonlinear dynamical systems is perhaps the validation of the

numerical solutions. As exact analytical solutions often do not exist, the validation of the

numerical algorithms relies heavily upon qualitative methods of analysis, such as phase

portraits or Poincare maps; as well as the theoretical context upon which the dynamics of the

system rest. For instance, when looking at an inverted pendulum in the context of classical

mechanics, one can make reasonable assumptions based on conservation laws. Some of these

assumptions may include:

1) The two-body inverted pendulum system should reduce to a simple pendulum if the cart is

fixed. One way to achieve this is to include an arbitrarily large frictional force on the cart.

2) In the absence of damping forces such as air drag and friction, there should be no energy

dissipation, and hence the system should oscillate infinitely and similar to simple harmonic

motion, with constant amplitude and frequency.

3) In the presence of damping forces, the system should lose energy and come to a stop after

a certain amount of time. If the damping coefficients are larger, then the energy dissipation

rate should also increase, and the stoppage time should decrease.

4) If the mass of the pendulum is significantly larger than that of the cart, then the system

should take much longer to come to a stop. Alternatively, if the cart has a much larger mass

than the pendulum, it should take less time to reach static equilibrium.

Similar assumptions can be made for any other two-body classical system. Therefore, the

algorithm should be easily implementable for other two-body systems, such as the double

pendulum and the coupled oscillator, by simply changing the equations of motion, as is shown

in Appendix B.

3. Background Theory

3.1. Numerical derivatives

The numerical solution to ordinary differential equations has been one of the most useful tools

implemented in science and engineering since the advent of computers. As many differential

equations of interest are non-linear in nature, it is often necessary to resort to numerical

approximations to find solutions where mathematical analysis simply cannot. Many methods

have been developed, each one with a different degree of accuracy and numerical stability;

such as the Euler and Runge-Kutta methods [1, 2].

All these methods have something in common: they exploit the concept of finite differences

which arise from truncating the derivative of a function up to a certain error term. For instance,

consider the fundamental definition of a derivative:

𝑑𝑦

𝑑𝑥= lim

ℎ→0

𝑦(𝑥 + ℎ) − 𝑦(𝑥)

Page 4: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

4

This can be approximated by getting rid of the limit, and thus introducing a truncation error

𝑂(ℎ𝑛) which is proportional to the step-size ℎ to some order 𝑛:

𝑑𝑦

𝑑𝑥≈𝑦(𝑥 + ℎ) − 𝑦(𝑥)

ℎ+ 𝑂(ℎ𝑛)

The idea of the numerical approximation is to minimise the error 𝜖 between the numerical

solution and the analytical solution, such that:

|limℎ→0

𝑦(𝑥 + ℎ) − 𝑦(𝑥)

ℎ− [𝑦(𝑥 + ℎ) − 𝑦(𝑥)

ℎ+ 𝑂(ℎ𝑛)]| < 𝜖

At every point 𝑥 = 𝑥𝑘 where 𝑘 ∈ ℤ+. This same concept can be extended to the solution of

differential equations, as will be demonstrated in this paper. For example, a simple differential

equation such as:

𝑑𝑦

𝑑𝑥= 𝑘𝑦

Can be solved by replacing the derivative with a finite approximation, and then solving for the

term 𝑦(𝑥 + ℎ) which is the step forward in time:

𝑦(𝑥 + ℎ) − 𝑦(𝑥)

ℎ= 𝑘𝑦 → 𝑦(𝑥 + ℎ) = 𝑦(𝑥) + ℎ𝑘𝑦(𝑥)

And thus, this can be rewritten as a difference equation:

𝑦𝑛+1 = 𝑦𝑛 + ℎ𝑘𝑦𝑛

Where the next value 𝑦𝑛+1 depends solely on the previous value 𝑦𝑛 and implicitly on time. The

equation is now a simple algebraic equation in which each of the variables is replaced by a

number for each value of time. The solution is built upon numerous iterations of this same

equation. A computer can perform this task by using a prescribed number of iterations, and the

more iterations that are used the more accurate the approximation will be (this is known as

numerical convergence). The Runge-Kutta method for instance converges very rapidly with

decreasing step-size, so normally we refer to this as good numerical stability. The Euler method,

in the other hand, often diverges if the step-size is not large enough, so the numerical stability

is lower than for the Runge-Kutta method [1]. There is, however, a trade-off between accuracy

and computation time that must be taken into account.

3.2. The Runge-Kutta algorithm

The Runge-Kutta method [1] consists on using a Taylor series expansion in order to

approximate the value of a derivative and transform a differential equation into a difference

equation that can be solved numerically with high accuracy and relatively low computation

time. The order of the RK approximation is determined by the order of the truncation error in

the expansion. Generally, an 𝑛th order RK has a local truncation error 𝑂(ℎ𝑛+1). By expressing

a first order differential equation in the form 𝑦′(𝑡) = 𝑓(𝑡, 𝑦(𝑡)), the RK4 is usually defined by

the following difference equation [1]:

𝑦𝑛+1 = 𝑦𝑛 +ℎ

6(𝑘1 + 2𝑘2 + 2𝑘3 + 𝑘4)

Page 5: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

5

𝑘1 = 𝑓(𝑡𝑛 , 𝑦𝑛)

𝑘2 = 𝑓 (𝑡𝑛 +ℎ

2, 𝑦𝑛 +

ℎ𝑘12)

𝑘3 = 𝑓 (𝑡𝑛 +ℎ

2, 𝑦𝑛 +

ℎ𝑘22)

𝑘4 = 𝑓(𝑡𝑛 + ℎ, 𝑦𝑛 + ℎ𝑘3)

The RK4 algorithm can be implemented to solve any type of differential equation, including

nonlinear ones; with reasonable accuracy. It is well-behaved and usually stable for step-sizes

smaller than 10-4. One of the limitations of this algorithm, however; is that it only works with

first order differential equations. As with the Euler method, the user must convert any higher

order differential equation into a first order system by performing a change of variables. This

means that for an 𝑛th order differential equation, there will be 𝑛 first order difference equations

that need to be put into the algorithm. The same applies for systems of equations. Another

limitation arises from differential equations that are coupled or co-dependent in terms of second

derivatives. To implement the algorithm, the equations must first be uncoupled by algebraic

methods (where applicable), before they can be solved.

Despite these minor drawbacks, the RK4 algorithm is very useful for the analysis of physical

dynamical systems, in particular for those in classical mechanics as is the inverted pendulum.

3.3.Dynamics of the inverted pendulum

The inverted pendulum studied in this paper is similar to that shown in figure 1. It consists of

three components: the bob, the rod and the cart. For simplicity, the rod is assumed to be

massless. The reason for this assumption comes from the fact that if the rod had mass, the

centre of mass of the pendulum would simply be shifted below the bob by a certain amount. In

practical scenarios involving a pendulum, the bob is usually more massive than the rod, so the

assumption holds. Another assumption that was made in the analysis was that there is no

friction between connected components (e.g. the ball bearings in the pivot of the pendulum are

completely smooth). Additionally, the pendulum is free to swing on a 360o path, as the cart

stands on a set of rails that allow the pendulum to swing freely between them.

Figure 1. Basic diagram of the inverted pendulum and cart.

Page 6: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

6

To make the system more realistic, air drag acting on the pendulum and friction on the cart

have been added to the simulation in order to observe how the presence of small damping forces

can significantly alter the system’s motion.

The equations of motion are derived fully in appendix B. These are:

{2𝐿�̈� + �̈� cos 𝜃 − 𝑔 sin 𝜃 +

𝜇𝐷𝑚�̇� = 0

(𝑚 +𝑀

𝑚𝐿) �̈� + �̈� cos 𝜃 − �̇�2 sin 𝜃 −

𝜇𝐷𝑚𝐿

�̇� cos𝜃 +𝜇𝐹𝑚𝐿

�̇� = 0

The dimensions of the bob have been ignored in order to treat it as a particle mass, which means

its mass moment of inertia reduces to 𝐼 = 𝑚𝐿2 . This a system of two coupled 2nd order

nonlinear differential equations. This system accounts for air drag and friction forces, and by

setting the corresponding damping coefficients to zero; it reduces to the simpler case where

there are no energy losses and the system oscillates infinitely. The addition of damping forces

however, forces the system to lose energy gradually and thus comes to rest after a certain period

of time [2, 3]. These are the types of behaviours that are observed in the simulation. For more

information on the derivation of these equations and the algorithm, see appendix B.

4. Simulation Details

The simulation was run several times using four sets of parameters, one for each of the

assumptions described in the introduction. Most of the parameters were kept constant during

the simulation stage. Units are outlined in the nomenclature. The cases considered are:

1) Case 1: large friction on the cart. The cart should have minimal displacement and appear

to remain fixed throughout the pendulum’s motion, while the pendulum behaves as a simple

pendulum.

2) Case 2: no damping forces. The system should reduce to simple harmonic motion, or at

least oscillate without losing any energy.

3) Case 3: damping forces present, including air drag and cart friction. The system should lose

energy with time, so the oscillations are expected to decay rapidly as a result of the energy

dissipation.

4) Case 4: large pendulum mass compared to cart. Having a larger pendulum mass should give

the system more potential energy, which means the oscillations on the pendulum should

decay more slowly with time, and thus the amplitude of the oscillations on the cart should

be larger and increase with increasing pendulum mass.

Each of these four cases corresponds to the assumptions stated in the introduction. The

parameters are summarised in table 1.

Table 1 – Input parameters for simulation in each of the four cases investigated

Parameter Symbol Case 1 Case 2 Case 3 Case 4

Number of data points 𝑛 10,000 10,000 10,000 10,000

Step-size ℎ 0.004 0.004 0.004 0.004

Mass of the pendulum 𝑚 1 1 1 100

Mass of the cart 𝑀 2 2 2 2

Length of the pendulum 𝐿 1 1 1 1

Gravitational constant 𝑔 9.81 9.81 9.81 9.81

Page 7: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

7

Initial time 𝑡0 0 0 0 0

Initial angular displacement of the

pendulum 𝜃0 0.3 0.3 0.3 0.3

Initial angular velocity of the pendulum 𝜔0 0 0 0 0

Initial displacement of the cart 𝑋0 0 0 0 0

Initial velocity of the cart 𝑣0 0 0 0 0

Damping coefficient of air drag 𝜇𝐷 0 0 0.5 0.5

Damping coefficient of friction 𝜇𝐹 1,000 0 0.5 0.5

Additionally, the program produces an animation that shows the behaviour of the system, as

portrayed in figure 2.

Figure 2. Screenshot of animation from program.

5. Validation

In order to show the convergence of the RK4 algorithm, a simple pendulum was modelled

using the small angle approximation and thus the numerical solution was compared to the

analytical solution, using different step sizes. The equation of motion for a simple pendulum is

common-place in physics courses and can be found in any standard book on mechanics, as in

Leonard’s Susskind’s “Classical Mechanics: The Theoretical Minimum” [3]. The equation of

motion is thus:

�̈� +𝑔

𝐿𝜃 = 0

For the linearized case sin 𝜃 ≈ 𝜃 (valid between 0 and 0.26 radians). This equation has the

general solution:

𝜃(𝑡) = 𝜃0 cos(𝑡√𝑔

𝐿)

Where 𝜃0 is the initial angle and 𝐿 is the length of the rod. The parameters for the simulation

were: 𝜃0 = 0.1 rad, mass of 1 kg, length of 1 m, and gravitational constant of 9.81 m/s2. The

code can be found in Appendix C.4.

Page 8: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

8

The error analysis consisted of calculating the global error for each of the solutions given

different step sizes. Setting the step-size as ℎ = 5/𝑛 for a time-scale of 5 seconds, the number

of steps selected for the simulation were: 102, 103, 104, 105 and 106. The global error was

calculated as the sum of the absolute difference between the analytical solution and the

numerical solution for each step-size:

𝜖𝑔𝑙𝑜𝑏𝑎𝑙 =∑|𝜃𝑘𝑎𝑛𝑎𝑙𝑦𝑡𝑖𝑐

− 𝜃𝑘𝑛𝑢𝑚𝑒𝑟𝑖𝑐𝑎𝑙 |

𝑛

𝑘=1

According to the definition of the RK4 algorithm, the global error should be proportional to ℎ4

[1]. Figure 3 shows a comparison of the analytical solution to the numerical solution for a step

size of 5×10-6. It can be observed that both solutions look identical in this scale, suggesting the

approximation obtained from the RK4 algorithm with this step-size is very accurate.

Additionally, the numerical solution shows good stability as the oscillations remain constant,

as they should from the conditions imposed (no energy dissipation as there are no damping

forces present in the system).

Figure 3. Numerical solution from RK4 algorithm for a step-size of 5×10-6 (left), and

analytical solution (right).

The global error variation with step-size is shown in figure 4 below. As can be observed from

this graph, the error decreases linearly with decreasing step-size, as expected. What is even

more important to point out is how rapidly the global error converges with decreasing step-size,

as it comes very close to 0 for a step size of 0.005. In the case of the step-size of 5×10-6, as

shown in figure 3; the global error is almost negligible, and approaches zero very rapidly as

ℎ < 0.005. This suggests that the RK4 algorithm as implemented in this program works as is

expected, and that it is a very suitable choice for modelling nonlinear systems.

Page 9: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

9

Figure 4. Global error as a function of step-size on RK4 method for simple pendulum

system.

6. Results and Discussion

6.1.Case 1: large friction on cart – reduction to simple pendulum system

The following results were produced:

Figure 5. Angular displacement of

pendulum with respect to time.

Figure 6. Linear displacement of cart with

respect to time.

Page 10: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

10

Figure 7. Angular velocity of pendulum

with respect to time.

Figure 8. Velocity of cart with respect to

time.

Figure 9. Phase portrait of displacements.

Figure 10. Phase portrait of velocities.

Figures 5 and 6 show how the pendulum approximates simple harmonic motion when the

coefficient for damping due to friction on the cart is set to 1,000 N.s/m. However, it can also

be observed that the system deviates slightly as the amplitude of the oscillations decays

gradually with time, which suggests there is a certain amount of energy dissipation still present

in the system. This is due to the fact that the damping coefficient would need to be infinite in

order for the system to approach the simple pendulum exactly, and given that the program can

only work with finite values, there is bound to be some error in it.

Figures 6 and 8 show how the cart is not static under these conditions, but rather exhibits a very

small displacement in comparison to the pendulum. This is expected as the large friction

coefficient is not enough to force the cart into static equilibrium. These effects can be visualized

more clearly in the two phase portraits in figures 9 and 10. The closely-packed contours suggest

that the system is slightly unstable in the presence of a movable cart as the pivot point for the

pendulum. However, it can also be seen that the cart has a displacement which directly affects

the motion of the pendulum.

6.2.Case 2: zero damping forces – reduction to simple harmonic motion

Page 11: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

11

Figure 11. Angular displacement of

pendulum with respect to time.

Figure 12. Linear displacement of cart with

respect to time.

Figure 13. Angular velocity of pendulum

with respect to time.

Figure 14. Velocity of cart with respect to

time.

Figure 15. Phase portrait of displacements.

Figure 16. Phase portrait of velocities.

In the absence of damping forces, the system should not lose any energy with time and thus the

pendulum and cart should oscillate with constant amplitude and frequency. The system behaves

as expected in the simulation, as can be seen in figures 11 – 16. The phase portraits in figures

15 and 16 show how the system follows a single path, as opposed to case 1 in which there were

concentric contours due to the cart’s constrained motion. This suggests that the system is a lot

more stable under these conditions, and that it will not deviate from its main trajectory if the

Page 12: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

12

initial conditions are changed. Figures 13 and 14 illustrate how the respective angular velocity

of the pendulum and the velocity of the cart vary with time. The pendulum’s velocity has sharp

peaks and steep gradients, suggesting that it is being forced in different directions by the cart,

and the cart itself suffers from irregular oscillations as a result from the effect of the pendulum’s

mass. Each of the object’s inertia affects the other, and this exchange causes the system’s

behaviour to be more complex.

Despite the nonlinear behaviour exhibited in this case, the pendulum resembles simple

harmonic motion in having a constant amplitude and frequency, and it does not decay with

time as it did in case 1. Therefore, this is a good indicator that the system behaves as expected

and attains to assumption number 2.

6.3. Case 3: damping forces present

Figure 16. Angular displacement of

pendulum with respect to time.

Figure 17. Linear displacement of cart with

respect to time.

Figure 18. Angular velocity of pendulum

with respect to time.

Figure 19. Velocity of cart with respect to

time.

Page 13: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

13

Figure 20. Phase portrait of displacements.

Figure 21. Phase portrait of velocities.

This simulation shows more interesting chaotic behaviours. By adding damping forces with

coefficients of 0.5 N.s/m, the system loses energy very rapidly and within 40 seconds the

oscillations decay to almost zero. Figures 17 and 18 show how the displacement of the

pendulum and cart decay exponentially as predicted by assumption number 3. The cart’s

displacement is shifted to one side within the first 20 seconds of the motion, as it first moves

to the left when the pendulum swings anti-clockwise.

Figure 21 shows a nodal sink for the pendulum when the angular displacement is nearly 𝜋

radians (this is the state with the pendulum pointing vertically down, so it will not swing), and

thus the system will tend to remain in this state as the pendulum will have zero potential energy

when this condition is met. However, it can also be observed from this diagram that the system

is very unstable for all other initial conditions, but it will always tend to this point at which the

angle is 𝜋 radians and the displacement of the cart is nearly 0.3 metres towards the left of the

x-axis. This is mainly due to the starting position of the pendulum with respect to the cart.

Similarly, figure 22 shows a nodal sink at the origin for the velocities of the pendulum and cart.

This also suggests that for any starting position of the pendulum, its velocity will tend to zero

after a certain number of cycles, though there is no symmetry in the trajectories. By increasing

the values of the damping coefficients, the simulation also showed that oscillations decay more

abruptly and reach zero in a shorter period of time, which is also in agreement with assumption

number 3.

6.4. Case 4: relationship between mass of the pendulum and cart

Figure 22. Angular displacement of

pendulum with respect to time.

Figure 23. Linear displacement of cart with

respect to time.

Page 14: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

14

Figure 24. Angular velocity of pendulum

with respect to time.

Figure 25. Velocity of cart with respect to

time.

Figure 26. Phase portrait of displacements.

Figure 27. Phase portrait of velocities.

Case 4 took into account a scenario in which the mass of the pendulum is 100 kg and the mass

of the cart remained at 2 kg. This large mass ratio of the pendulum has a significant effect on

the system’s motion. Figures 23 and 25 show how the pendulum’s angular displacement and

velocity approach the results obtained for case 1. The oscillations still decay but more slowly

than in case 3, even with the presence of damping forces. This is due to the high potential

energy stored in the pendulum which results from its larger mass. In this manner, the pendulum

behaves as if the cart were fixed, though it is mobile. Figures 24 and 26 illustrate this in more

detail, and what can be observed is how the cart behaves as it did in case two in the absence of

damping forces, but with a small rate of decay in oscillations. This suggests that increasing the

mass of the pendulum causes the system’s dynamics to become a combination of case 1 and 2.

However, figures 26 and 27 show many more curves in the phase plots, so the overall trajectory

space is wider than that observed in case 2 in the absence of damping forces. The reason for

this is that despite the system approaching a simple harmonic motion within this interval of

time, it is clear that damping forces are present and they play a role in the overall loss of energy

in the system, even if the initial potential energy of the system is much larger than in the other

3 cases.

Page 15: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

15

7. Conclusions

In this investigation, the RK4 algorithm was tested and applied in the simulation of an inverted

pendulum system, using the nonlinear coupled differential equations that can be derived

through Lagrangian or Newtonian methods, as shown in Appendix A. The analysis of the

system took into account the effects of damping forces such as air drag and friction, as well as

variations in mass between the bodies and how these changes affected the dynamics of the

system. Furthermore, the code was adjusted so it could be easily implemented to other two-

body systems, such as the double-pendulum and couple harmonic oscillator, as shown in

Appendix B. Despite the limitations in the validation of the results, the program should serve

as a platform for future studies of multi-body systems in physics, and help undergraduate

students understand the process of problem definition, derivation, discretisation and

quantification; and provide them with a valuable approach to problem solving, applicable not

only in the realm of computational sciences but in other areas alike.

8. Limitations and recommendations for further improvement

Clear limitations in the program include the inability to compare the inverted pendulum

system’s numerical solutions to analytical solutions, as there are none which can be found

through any mathematical methods. This makes the validation of the code or the quantification

of the accuracy of the numerical approximations very challenging, as the only measure of

accuracy can be provided by the convergence of the RK4 algorithm itself. However,

convergence does not necessarily imply correctness of the solutions, so the next best avenue

for analysis are qualitative methods as the ones implemented in the analysis of the results

shown in this paper. Nevertheless, qualitative methods of analysis still pose some challenges

in terms of computation. For instance, the phase plots produced in the results section are

simplified versions of actual phase portraits which can be found in nonlinear dynamics

textbooks, such as those in [5, 6]. The reason for this is that the computer that was used for the

simulations lacked RAM to actually produce vector fields based on the selected number of

steps (104). In fact, MATLAB was unable to produce vector field plots using the “quiver”

function for 𝑛 as little as 103, as the computer kept getting depleted of RAM even with all

background processes at a minimum. For this reason, qualitative analysis could not be

performed to its fullest either due to hardware limitations. Perhaps a way in which this can be

fixed to some extent would be to explore methods of parallel computing or GPU computing,

which make better use of available resources through coupling with VRAM and multiple

processors.

On the simulation end, although the program performs as expected and exhibits a good amount

of stability, it still requires the user to understand programming in MATLAB in order to

implement it. Changes to initial conditions can only be done in the script itself, and there is no

graphical user interface. The animation code needs to be changed for each particular system.

In this manner, improvements could be done on the program by adding a graphical user

interface in which all input parameters and equations of motion can be fed to the program, so

that it automatically solves them and displays a variety of graphics and animations.

Additionally, the GUI could contain an option for selecting the shapes used in the animation,

or even importing images in PNG or JPEG formats that could be used as the objects in the

animations. An even more functional feature would be to develop an algorithm that can solve

Page 16: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

16

a system of 𝑁 differential equations of 𝑛 order, as specified by the user, rather than being

limited to two-body systems.

Acknowledgements

I would like to acknowledge the constant support and guidance provided by Angus Gentle and

Matthew Arnold in the completion of this project. Additionally, I would like to acknowledge

the help of my peers, particularly of Sharnan Kemp, Blake Regan and Tristan Walsh, who

provided constant feedback and also suggested ways for improving the code and its capabilities.

References

1. Klein, A., Godunov, A., 2006. Introductory Computational Physics, Ch.1, 5 and 8.

Cambridge University Press, United Kingdom.

2. Stewart, J., 2015. Calculus: Early Transcendentals. Cengage Learning.

3. Susskind, L., Hrabovsky, G., 2014, Classical Mechanics: The Theoretical Minimum.

Penguin Press.

4. Rafat, M.Z., Wheatland, M.S. and Bedding, T.R., 2009. Dynamics of a double pendulum

with distributed mass. American Journal of Physics, 77(3), pp.216-223.

5. Lam, L., 1998. Nonlinear physics for beginners: fractals, chaos, solitons, pattern formation,

cellular automata, complex systems. World Scientific.

6. Strogatz, S.H., 2014. Nonlinear dynamics and chaos: with applications to physics, biology,

chemistry, and engineering. Westview press.

7. Davis, T.A., 2010. MATLAB primer. CRC press.

Page 17: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

17

Appendix A – Derivation of equations of motion

The case for no external forces using the Lagrangian method

*Note: all the images presented in this appendix were drawn by the author using the image and

shape tools provided on Microsoft Word.

The simplest case possible for the analysis assumes that the pendulum has no external force

acting on it (e.g. the forcing term is zero). It only takes into account the initial angular

displacement of the pendulum, and that the mass of the ball is much larger than the mass of the

rod connecting it to the cart, so that the centre of mass is shifted up and can be approximated

by a model that ignores the mass of the rod itself. We may start by looking at a simplified

diagram:

The orange arrow shows the displacement of the cart’s centre of mass, which is where the

pendulum is attached. Using simple trigonometry, we may express the coordinates of the

pendulum (𝑥, 𝑦) in terms of the angular displacement 𝜃(𝑡):

𝑥 = 𝐿 sin 𝜃 ; 𝑦 = 𝐿 cos𝜃

However, the horizontal displacement of the pendulum is also dependent on the displacement

of the cart 𝑋(𝑡) so we must include this term in the relationship:

𝑥 = 𝑋 + 𝐿 sin 𝜃 ; 𝑦 = 𝐿 cos 𝜃

Differentiating with respect to time to obtain the velocities, we get:

�̇� = �̇� + 𝐿�̇� cos𝜃 ; �̇� = −𝐿�̇� sin 𝜃

Thus:

�̇�2 = �̇�2 + 2𝐿�̇��̇� cos 𝜃 + 𝐿2�̇�2 cos2 𝜃 ; �̇�2 = 𝐿2�̇�2 sin2 𝜃

This leads to the combined kinetic energy of the pendulum, which includes the rotational

kinetic energy:

Page 18: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

18

𝑇𝑝𝑒𝑛𝑑𝑢𝑙𝑢𝑚 =1

2𝑚(�̇�2 + �̇�2) +

1

2𝐼�̇�2

=1

2𝑚(�̇�2 + 2𝐿�̇��̇� cos𝜃 + 𝐿2�̇�2 cos2 𝜃 + 𝐿2�̇�2 sin2 𝜃) +

1

2𝐼�̇�2

∴ 𝑇𝑝𝑒𝑛𝑑𝑢𝑙𝑢𝑚 =1

2𝑚(�̇�2 + 2𝐿�̇��̇� cos𝜃 + 𝐿2�̇�2) +

1

2𝐼�̇�2

And its potential energy will just be due to its weight:

𝑉𝑝𝑒𝑛𝑑𝑢𝑙𝑢𝑚 = 𝑚𝑔𝑦 = 𝑚𝑔𝐿 cos 𝜃

So that the Lagrangian for the pendulum becomes:

𝐿𝑝𝑒𝑛𝑑𝑢𝑙𝑢𝑚 = 𝑇𝑝𝑒𝑛𝑑𝑢𝑙𝑢𝑚 − 𝑉𝑝𝑒𝑛𝑑𝑢𝑙𝑢𝑚

=1

2𝑚(�̇�2 + 2𝐿�̇��̇� cos𝜃 + 𝐿2�̇�2) +

1

2𝐼�̇�2 −𝑚𝑔𝐿 cos𝜃

For the cart, the potential energy will be zero since it remains horizontal the whole time.

However, its kinetic energy will only be linear in the 𝑥 direction:

𝑇𝑐𝑎𝑟𝑡 =1

2𝑀�̇�2

So at this point we can combine these to obtain the Lagrangian of the entire system:

𝐿 = 𝐿𝑝𝑒𝑛𝑑𝑢𝑙𝑢𝑚 + 𝐿𝑐𝑎𝑟𝑡 =1

2𝑚(�̇�2 + 2𝐿�̇��̇� cos𝜃 + 𝐿2�̇�2) +

1

2𝐼�̇�2 +

1

2𝑀�̇�2 −𝑚𝑔𝐿 cos𝜃

This means the Lagrangian is a function of 4 variables: 𝐿(𝑡, 𝜃, �̇�, �̇�) . Hence the partial

derivatives are:

𝜕𝐿

𝜕𝑋= 0;

𝜕𝐿

𝜕�̇�= 𝑚�̇� +𝑀�̇� + 𝑚𝐿�̇� cos 𝜃 = (𝑚 +𝑀)�̇� +𝑚𝐿�̇� cos𝜃

𝑑

𝑑𝑡(𝜕𝐿

𝜕�̇�) = (𝑚 +𝑀)�̈� +𝑚𝐿�̈� cos𝜃 −𝑚𝐿�̇�2 sin 𝜃

𝜕𝐿

𝜕𝜃= −𝑚𝐿�̇��̇� sin 𝜃 +𝑚𝑔𝐿 sin 𝜃 = 𝑚𝐿 sin 𝜃 (𝑔 − �̇��̇�)

𝜕𝐿

𝜕�̇�= 𝑚𝐿�̇� cos𝜃 +𝑚𝐿2�̇� + 𝐼�̇�

𝑑

𝑑𝑡(𝜕𝐿

𝜕�̇�) = 𝑚𝐿�̈� cos𝜃 −𝑚𝐿�̇��̇� sin 𝜃 +𝑚𝐿2�̈� + 𝐼�̈�

Henceforth the Equations of motion are:

𝑑

𝑑𝑡(𝜕𝐿

𝜕�̇�) =

𝜕𝐿

𝜕𝜃

𝑚𝐿�̈� cos 𝜃 − 𝑚𝐿�̇��̇� sin 𝜃 + 𝑚𝐿2�̈� + 𝐼�̈� = 𝑚𝐿 sin 𝜃 (𝑔 − �̇��̇�)

Page 19: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

19

(𝐼 +𝑚𝐿2

𝑚𝐿) �̈� + �̈� cos𝜃 − 𝑔 sin 𝜃 = 0 − − − (1)

𝑑

𝑑𝑡(𝜕𝐿

𝜕�̇�) =

𝜕𝐿

𝜕𝑋

(𝑚 +𝑀

𝑚𝐿) �̈� + �̈� cos𝜃 − �̇�2 sin 𝜃 = 0 − − − (2)

The case for no external forces using the Newtonian method

Using the Newtonian method, we obtain the free body diagrams:

Pendulum Cart

Analysis of the pendulum:

To analyse the pendulum we must use two sets of equations: one for the translational motion,

and one of the rotational motion. We begin by considering the translational motion:

∑𝐹𝑥 = 𝑚𝑎𝑥 = −𝐹𝑥

∑𝐹𝑦 = 𝑚𝑎𝑦 = 𝐹𝑦 −𝑚𝑔

For the rotational motion, we consider the angular acceleration about the pendulum’s centre of

mass (the bob), so we have:

∑𝜏𝑚 = 𝐼𝛼 = 𝐹𝑦𝐿 sin 𝜃 + 𝐹𝑥𝐿 cos𝜃

However, one can perform an easy change of coordinates in order to express 𝑎𝑥 and 𝑎𝑦 in terms

of 𝜃. What we need to note here is that the position of the pendulum can be transformed into

polar coordinates:

𝑥 = 𝑋 + 𝐿 sin 𝜃 ; 𝑦 = 𝐿 cos 𝜃

Where 𝑋 is the displacement of point 𝐶, as the cart will move as well. Hence:

Page 20: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

20

𝑎𝑥 =𝑑2𝑥

𝑑𝑡2=𝑑

𝑑𝑡(𝑑(𝑋 + 𝐿 sin 𝜃)

𝑑𝑡) =

𝑑

𝑑𝑡(�̇� + 𝐿�̇� cos𝜃) = �̈� + 𝐿�̈� cos 𝜃 − 𝐿�̇�2 sin 𝜃

𝑎𝑦 =𝑑2𝑦

𝑑𝑡2=𝑑

𝑑𝑡(𝑑(𝐿 cos 𝜃)

𝑑𝑡) =

𝑑

𝑑𝑡(−𝐿�̇� sin 𝜃) = −𝐿�̈� sin 𝜃 − 𝐿�̇�2 cos𝜃

Which leads to:

𝐹𝑥 = −𝑚𝑎𝑥 = −𝑚�̈� − 𝑚𝐿�̈� cos 𝜃 + 𝑚𝐿�̇�2 sin 𝜃

𝐹𝑦 = 𝑚𝑔 + 𝑚𝑎𝑦 = 𝑚𝑔 −𝑚𝐿�̈� sin 𝜃 −𝑚𝐿�̇�2 cos 𝜃

Putting these into ∑𝜏𝑚 = 𝐼𝛼 leads to:

𝐼�̈� = 𝐹𝑦𝐿 sin 𝜃 + 𝐹𝑥𝐿 cos𝜃

𝐼�̈� = 𝐿 sin 𝜃 (𝑚𝑔 − 𝑚𝐿�̈� sin 𝜃 − 𝑚𝐿�̇�2 cos𝜃) + 𝐿 cos𝜃 (𝑚𝐿�̇�2 sin 𝜃 −𝑚�̈� −𝑚𝐿�̈� cos𝜃)

𝐼�̈� = 𝑚𝑔𝐿 sin 𝜃 − 𝑚𝐿2�̈� − 𝑚𝐿�̈� cos 𝜃

(𝐼 + 𝑚𝐿2

𝑚𝐿) �̈� + �̈� cos𝜃 − 𝑔 sin 𝜃 = 0 − − − (1)

Analysis of the cart:

To analyse the cart we will assume that there is no friction on it (after all, the system we are

modelling is free to roll). We only have to take into account translational motion:

∑𝐹𝑥 = 𝑀�̈� = 𝐹𝑥

∑𝐹𝑦 = 0 = 𝑁 −𝑀𝑔 − 𝐹𝑦 → 𝐹𝑦 = 𝑁 −𝑀𝑔

However, we know that:

𝐹𝑥 = −𝑚�̈� − 𝑚𝐿�̈� cos 𝜃 + 𝑚𝐿�̇�2 sin 𝜃 = 𝑀�̈�

𝑀�̈� + 𝑚�̈� + 𝑚𝐿�̈� cos𝜃 − 𝑚𝐿�̇�2 sin 𝜃 = 0

(𝑚 +𝑀

𝑚𝐿) �̈� + �̈� cos𝜃 − �̇�2 sin 𝜃 = 0 − − − (2)

And as we can see, this gives us the exact same equations of motion as the Lagrangian method,

which validates them. At this point it would be possible to convert these into suitable difference

equations that can be put into the RK4 algorithm, but it is more useful to look at the even more

general case where there are external forces on the system. Naturally, such equations of

motions would reduce to the ones shown above if all external forces are set to zero.

The case including external forces

Consider once again the same system, only that now we introduce a disturbance in the form of

damping forces, one affecting the pendulum’s motion and another one acting on the cart’s

motion. The corresponding free body diagrams become:

Page 21: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

21

Pendulum Cart

Here we cannot use the Lagrangian method because it does not take into account the effect of

external forces, such as friction or damping forces as in this case. So we must use the

Newtonian method instead.

Analysis of the pendulum:

The procedure is the same as before, with the only difference that we now include the force

𝐹(𝑡) into the equations. For convenience, we will label it as 𝐹:

∑𝐹𝑥 = 𝑚𝑎𝑥 = −𝐹𝑥 − 𝐷 cos 𝜃

∑𝐹𝑦 = 𝑚𝑎𝑦 = 𝐹𝑦 −𝑚𝑔 + 𝐷 sin 𝜃

For the rotational motion, we consider the angular acceleration about the pendulum’s centre of

mass (the bob), so we have:

∑𝜏𝑚 = 𝐼𝛼 = 𝐹𝑦𝐿 sin 𝜃 + 𝐹𝑥𝐿 cos𝜃

We now use the same coordinate transformation:

𝑥 = 𝑋 + 𝐿 sin 𝜃 ; 𝑦 = 𝐿 cos 𝜃

So that:

𝑎𝑥 =𝑑2𝑥

𝑑𝑡2=𝑑

𝑑𝑡(𝑑(𝑋 + 𝐿 sin 𝜃)

𝑑𝑡) =

𝑑

𝑑𝑡(�̇� + 𝐿�̇� cos𝜃) = �̈� + 𝐿�̈� cos 𝜃 − 𝐿�̇�2 sin 𝜃

𝑎𝑦 =𝑑2𝑦

𝑑𝑡2=𝑑

𝑑𝑡(𝑑(𝐿 cos 𝜃)

𝑑𝑡) =

𝑑

𝑑𝑡(−𝐿�̇� sin 𝜃) = −𝐿�̈� sin 𝜃 − 𝐿�̇�2 cos𝜃

Which leads to:

𝐹𝑥 = −𝑚𝑎𝑥 − 𝐷 cos 𝜃 = −𝑚�̈� − 𝑚𝐿�̈� cos 𝜃 + 𝑚𝐿�̇�2 sin 𝜃 − 𝐷 cos𝜃

𝐹𝑦 = 𝑚𝑔 +𝑚𝑎𝑦 −𝐷 sin 𝜃 = 𝑚𝑔 − 𝑚𝐿�̈� sin 𝜃 −𝑚𝐿�̇�2 cos 𝜃 − 𝐷 sin 𝜃

Putting these into ∑𝜏𝑚 = 𝐼𝛼 leads to:

Page 22: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

22

𝐼�̈� = 𝐹𝑦𝐿 sin 𝜃 + 𝐹𝑥𝐿 cos𝜃

𝐼�̈� = 𝐿 sin 𝜃 (𝑚𝑔 −𝑚𝐿�̈� sin 𝜃 −𝑚𝐿�̇�2 cos 𝜃 − 𝐷 sin 𝜃)

+ 𝐿 cos 𝜃 (𝑚𝐿�̇�2 sin 𝜃 − 𝑚�̈� − 𝑚𝐿�̈� cos 𝜃 − 𝐷 cos 𝜃)

𝐼�̈� = 𝑚𝑔𝐿 sin 𝜃 − 𝑚𝐿2�̈� − 𝑚𝐿�̈� cos 𝜃 − 𝐿𝐷

(𝐼 +𝑚𝐿2

𝑚𝐿) �̈� + �̈� cos 𝜃 − 𝑔 sin 𝜃 +

1

𝑚𝐷 = 0 − − − (1)

Analysis of the cart:

The sum of the forces are:

∑𝐹𝑥 = 𝑀�̈� = 𝐹𝑥 − 𝐹 → 𝐹𝑥 = 𝑀�̈� + 𝐹

∑𝐹𝑦 = 0 = 𝑁 −𝑀𝑔 − 𝐹𝑦 → 𝐹𝑦 = 𝑁 −𝑀𝑔

Taking the horizontal motion only into account, we get:

𝐹𝑥 = −𝑚�̈� − 𝑚𝐿�̈� cos 𝜃 + 𝑚𝐿�̇�2 sin 𝜃 − 𝐷 cos 𝜃 = 𝑀�̈� + 𝐹

𝑀�̈� + 𝑚�̈� +𝑚𝐿�̈� cos𝜃 − 𝑚𝐿�̇�2 sin 𝜃 − 𝐷 cos𝜃 + 𝐹 = 0

(𝑚 +𝑀

𝑚𝐿) �̈� + �̈� cos 𝜃 − �̇�2 sin 𝜃 −

1

𝑚𝐿𝐷 cos 𝜃 +

1

𝑚𝐿𝐹 = 0 − − − (2)

This leads to the system of two coupled nonlinear ordinary differential equations, which forms

a chaotic system:

{

(

𝐼 +𝑚𝐿2

𝑚𝐿) �̈� + �̈� cos 𝜃 − 𝑔 sin 𝜃 +

1

𝑚𝐷 = 0

(𝑚 +𝑀

𝑚𝐿) �̈� + �̈� cos 𝜃 − �̇�2 sin 𝜃 −

1

𝑚𝐿𝐷 cos 𝜃 +

1

𝑚𝐿𝐹 = 0

This system of equations accounts for any forces that may inhibit the system’s motion, and

generally 𝐷 will represent the net effect of all external forces acting on the pendulum, while 𝐹

will represent the net effect of all external forces acting on the cart. However, a few

assumptions have been made in this study:

- The dimensions of the bob (e.g. radius) are negligible. We can vary its mass by increasing

its density within the same volume.

- Since we are assuming that the mass of the bob is much larger than the mass of the rod it

is connected to, we can view the rod as being almost massless. This means that the bob is

treated as a point mass, and its moment of inertia will simply be its mass times the squared

distance from the centre of rotation: 𝐼 = 𝑚𝐿2.

With these assumptions, the above equations become:

Page 23: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

23

{2𝐿�̈� + �̈� cos 𝜃 − 𝑔 sin 𝜃 +

1

𝑚𝐷 = 0

(𝑚 +𝑀

𝑚𝐿) �̈� + �̈� cos 𝜃 − �̇�2 sin 𝜃 −

1

𝑚𝐿𝐷 cos 𝜃 +

1

𝑚𝐿𝐹 = 0

In general, we will consider the forces 𝐷 and 𝐹 to be related to air drag and friction,

respectively; as these are the most common external factors that would affect the system’s

dynamics in a practical scenario. Because both of these can be modelled as damping forces; we

can define them as:

𝐷 = 𝜇𝐷�̇�; 𝐹 = 𝜇𝐹�̇�

Where 𝜇𝐷 and 𝜇𝐹 are the respective damping coefficients in the two forces. These coefficients

can be chosen to have any values, as the magnitude of the two forces will increase with them.

Then the system of equations becomes:

{2𝐿�̈� + �̈� cos 𝜃 − 𝑔 sin 𝜃 +

𝜇𝐷𝑚�̇� = 0

(𝑚 +𝑀

𝑚𝐿) �̈� + �̈� cos 𝜃 − �̇�2 sin 𝜃 −

𝜇𝐷𝑚𝐿

�̇� cos𝜃 +𝜇𝐹𝑚𝐿

�̇� = 0

Which is a slightly more complicated dynamical system than the one with the free pendulum

and no friction.

Converting the nonlinear 2nd order ODEs into a system of 1st order ODEs

To solve this system, we should begin by re-arranging in a more convenient form such that we

can express the second-derivatives in terms of everything else.

{�̈� = −

1

2𝐿(�̈� cos 𝜃 − 𝑔 sin 𝜃 +

𝜇𝐷𝑚�̇�)

�̈� = −(𝑚𝐿

𝑚 +𝑀)(�̈� cos 𝜃 − �̇�2 sin 𝜃 −

𝜇𝐷𝑚𝐿

�̇� cos𝜃 +𝜇𝐹𝑚𝐿

�̇�)

Now we perform a change of variables:

𝑑𝜃

𝑑𝑡= 𝜔;

𝑑𝜔

𝑑𝑡=𝑑2𝜃

𝑑𝑡2= −

1

2𝐿(𝑑𝑣

𝑑𝑡cos𝜃 − 𝑔 sin 𝜃 +

𝜇𝐷𝑚𝜔)

𝑑𝑋

𝑑𝑡= 𝑣;

𝑑𝑣

𝑑𝑡=𝑑2𝑋

𝑑𝑡2= −(

𝑚𝐿

𝑚+𝑀)(𝑑𝜔

𝑑𝑡cos𝜃 − 𝜔2 sin 𝜃 −

𝜇𝐷𝑚𝐿

𝜔 cos𝜃 +𝜇𝐹𝑚𝐿

𝑣)

This allows for writing a system of four 1st order ODEs:

{

𝑑𝜃

𝑑𝑡= 𝜔

𝑑𝜔

𝑑𝑡= −

1

2𝐿(𝑑𝑣

𝑑𝑡cos𝜃 − 𝑔 sin 𝜃 +

𝜇𝐷𝑚𝜔)

𝑑𝑋

𝑑𝑡= 𝑣

𝑑𝑣

𝑑𝑡= −(

𝑚𝐿

𝑚 +𝑀)(𝑑𝜔

𝑑𝑡cos 𝜃 − 𝜔2 sin 𝜃 −

𝜇𝐷𝑚𝐿

𝜔 cos 𝜃 +𝜇𝐹𝑚𝐿

𝑣)

Page 24: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

24

Expressing these as a system of difference equations suitable for the RK4 algorithm yields:

𝜃(𝑡) =

{

𝜃𝑛+1 = 𝜃𝑛 +

6(𝑘𝜃1 + 2𝑘𝜃2 + 2𝑘𝜃3 + 𝑘𝜃4)

𝑘𝜃1 = 𝑓1(𝑡𝑛 , 𝜃𝑛𝜔𝑛 , 𝑋𝑛 , 𝑣𝑛) = 𝜔𝑛

𝑘𝜃2 = 𝑓1 (𝑡𝑛 +ℎ

2, 𝜃𝑛 +

ℎ𝑘𝜃12

,𝜔𝑛 +ℎ𝑘𝜔12

, 𝑋𝑛 +ℎ𝑘𝑋12

, 𝑣𝑛 +ℎ𝑘𝑣12)

𝑘𝜃3 = 𝑓1 (𝑡𝑛 +ℎ

2, 𝜃𝑛 +

ℎ𝑘𝜃22

,𝜔𝑛 +ℎ𝑘𝜔22

, 𝑋𝑛 +ℎ𝑘𝑋22

, 𝑣𝑛 +ℎ𝑘𝑣22)

𝑘𝜃4 = 𝑓1(𝑡𝑛 + ℎ, 𝜃𝑛 + ℎ𝑘𝜃3, 𝜔𝑛 + ℎ𝑘𝜔3, 𝑋𝑛 + ℎ𝑘𝑋3, 𝑣𝑛 + ℎ𝑘𝑣3)

𝜔(𝑡) =

{

𝜔𝑛+1 = 𝜔𝑛 +

6(𝑘𝜔1 + 2𝑘𝜔2 + 2𝑘𝜔3 + 𝑘𝜔4)

𝑘𝜔1 = 𝑓2(𝑡𝑛 , 𝜃𝑛𝜔𝑛𝑋𝑛 , 𝑣𝑛) = −1

2𝐿(𝑑𝑣𝑛𝑑𝑡

cos 𝜃𝑛 − 𝑔 sin 𝜃𝑛 +𝜇𝐷𝑚𝜔𝑛)

𝑘𝜔2 = 𝑓2 (𝑡𝑛 +ℎ

2, 𝜃𝑛 +

ℎ𝑘𝜃12

, 𝜔𝑛 +ℎ𝑘𝜔12

, 𝑋𝑛 +ℎ𝑘𝑋12

, 𝑣𝑛 +ℎ𝑘𝑣12)

𝑘𝜔3 = 𝑓2 (𝑡𝑛 +ℎ

2, 𝜃𝑛 +

ℎ𝑘𝜃22

, 𝜔𝑛 +ℎ𝑘𝜔22

, 𝑋𝑛 +ℎ𝑘𝑋22

, 𝑣𝑛 +ℎ𝑘𝑣22)

𝑘𝜔4 = 𝑓2(𝑡𝑛 + ℎ, 𝜃𝑛 + ℎ𝑘𝜃3, 𝜔𝑛 + ℎ𝑘𝜔3, 𝑋𝑛 + ℎ𝑘𝑋3, 𝑣𝑛 + ℎ𝑘𝑣3)

𝑋(𝑡) =

{

𝑋𝑛+1 = 𝑋𝑛 +

6(𝑘𝑋1 + 2𝑘𝑋2 + 2𝑘𝑋3 + 𝑘𝑋4)

𝑘𝑋1 = 𝑓3(𝑡𝑛 , 𝜃𝑛𝜔𝑛𝑋𝑛 , 𝑣𝑛) = 𝑣𝑛

𝑘𝑋2 = 𝑓3 (𝑡𝑛 +ℎ

2, 𝜃𝑛 +

ℎ𝑘𝜃12

,𝜔𝑛 +ℎ𝑘𝜔12

, 𝑋𝑛 +ℎ𝑘𝑋12

, 𝑣𝑛 +ℎ𝑘𝑣12)

𝑘𝑋3 = 𝑓3 (𝑡𝑛 +ℎ

2, 𝜃𝑛 +

ℎ𝑘𝜃22

,𝜔𝑛 +ℎ𝑘𝜔22

, 𝑋𝑛 +ℎ𝑘𝑋22

, 𝑣𝑛 +ℎ𝑘𝑣22)

𝑘𝑋4 = 𝑓3(𝑡𝑛 + ℎ, 𝜃𝑛 + ℎ𝑘𝜃3, 𝜔𝑛 + ℎ𝑘𝜔3, 𝑋𝑛 + ℎ𝑘𝑋3, 𝑣𝑛 + ℎ𝑘𝑣3)

𝑣(𝑡)

=

{

𝑣𝑛+1 = 𝑣𝑛 +

6(𝑘𝑣1 + 2𝑘𝑣2 + 2𝑘𝑣3 + 𝑘𝑣4)

𝑘𝑣1 = 𝑓4(𝑡𝑛 , 𝜃𝑛𝜔𝑛𝑋𝑛 , 𝑣𝑛) = −(𝑚𝐿

𝑚 +𝑀)(𝑑𝜔𝑛𝑑𝑡

cos 𝜃𝑛 −𝜔𝑛2 sin 𝜃𝑛 −

𝜇𝐷𝑚𝐿

𝜔𝑛 cos𝜃𝑛 +𝜇𝐹𝑚𝐿

𝑣𝑛)

𝑘𝑣2 = 𝑓4 (𝑡𝑛 +ℎ

2, 𝜃𝑛 +

ℎ𝑘𝜃12

, 𝜔𝑛 +ℎ𝑘𝜔12

, 𝑋𝑛 +ℎ𝑘𝑋12

, 𝑣𝑛 +ℎ𝑘𝑣12)

𝑘𝑣3 = 𝑓4 (𝑡𝑛 +ℎ

2, 𝜃𝑛 +

ℎ𝑘𝜃22

, 𝜔𝑛 +ℎ𝑘𝜔22

, 𝑋𝑛 +ℎ𝑘𝑋22

, 𝑣𝑛 +ℎ𝑘𝑣22)

𝑘𝑣4 = 𝑓4(𝑡𝑛 + ℎ, 𝜃𝑛 + ℎ𝑘𝜃3, 𝜔𝑛 + ℎ𝑘𝜔3, 𝑋𝑛 + ℎ𝑘𝑋3, 𝑣𝑛 + ℎ𝑘𝑣3)

Notice that here:

𝑑𝜔𝑛𝑑𝑡

= 𝑘𝜔1 = −1

2𝐿( 𝑘𝑣1 cos 𝜃𝑛 − 𝑔 sin 𝜃𝑛 +

𝜇𝐷𝑚𝜔𝑛)

𝑑𝑣𝑛𝑑𝑡

= 𝑘𝑣1 = −(𝑚𝐿

𝑚 +𝑀)(𝑘𝜔1 cos𝜃𝑛 − 𝜔𝑛

2 sin 𝜃𝑛 −𝜇𝐷𝑚𝐿

𝜔𝑛 cos 𝜃𝑛 +𝜇𝐹𝑚𝐿

𝑣𝑛)

Page 25: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

25

So there are two coupled equations. This is a major problem for the computer program because

it means that variables will be called before they are defined. In order to deal with this issue,

one could uncouple these two equations. Because the computer program reads them in the order

in which they are declared, we should solve for 𝑘𝜔1 first:

𝑘𝜔1 = −1

2𝐿( 𝑘𝑣1 cos 𝜃𝑛 − 𝑔 sin 𝜃𝑛 +

𝜇𝐷𝑚𝜔𝑛)

𝑘𝜔1 = −1

2𝐿( − (

𝑚𝐿

𝑚 +𝑀)(𝑘𝜔1 cos 𝜃𝑛 −𝜔𝑛

2 sin 𝜃𝑛 −𝜇𝐷𝑚𝐿

𝜔𝑛 cos𝜃𝑛 +𝜇𝐹𝑚𝐿

𝑣𝑛) cos 𝜃𝑛

− 𝑔 sin 𝜃𝑛 +𝜇𝐷𝑚𝜔𝑛)

𝑘𝜔1 =1

2(

𝑚

𝑚+𝑀)(𝑘𝜔1 cos𝜃𝑛 − 𝜔𝑛

2 sin 𝜃𝑛 −𝜇𝐷𝑚𝐿

𝜔𝑛 cos 𝜃𝑛 +𝜇𝐹𝑚𝐿

𝑣𝑛) cos𝜃𝑛 +𝑔

2𝐿sin 𝜃𝑛

−𝜇𝐷2𝑚𝐿

𝜔𝑛

𝑘𝜔1 =1

2(

𝑚

𝑚+𝑀)𝑘𝜔1 cos

2 𝜃𝑛 −1

2(

𝑚

𝑚+𝑀)𝜔𝑛

2 sin 𝜃𝑛 cos 𝜃𝑛 −𝜇𝐷2𝐿(

1

𝑚 +𝑀)𝜔𝑛 cos 𝜃𝑛

+𝜇𝐹2𝐿(

1

𝑚 +𝑀)𝑣𝑛 cos𝜃𝑛 +

𝑔

2𝐿sin 𝜃𝑛 −

𝜇𝐷2𝑚𝐿

𝜔𝑛

(1 −𝑚 cos2 𝜃𝑛2(𝑚 +𝑀)

)𝑘𝜔1 =𝑔

2𝐿sin 𝜃𝑛 −

𝑚𝜔𝑛2 sin 𝜃𝑛 cos 𝜃𝑛2(𝑚 +𝑀)

+(𝜇𝐹𝑣𝑛 − 𝜇𝐷𝜔𝑛) cos 𝜃𝑛

2𝐿(𝑚 +𝑀)−𝜇𝐷𝜔𝑛2𝑚𝐿

∴ 𝑘𝜔1 = (1 −𝑚 cos2 𝜃𝑛2(𝑚 +𝑀)

)

−1

[𝑔

2𝐿sin 𝜃𝑛 −

𝑚𝜔𝑛2 sin 𝜃𝑛 cos 𝜃𝑛2(𝑚 +𝑀)

+(𝜇𝐹𝑣𝑛 − 𝜇𝐷𝜔𝑛) cos𝜃𝑛

2𝐿(𝑚 +𝑀)

−𝜇𝐷𝜔𝑛2𝑚𝐿

]

Therefore the two equations become:

𝑑𝜔𝑛𝑑𝑡

= 𝑘𝜔1 = (1 −𝑚 cos2 𝜃𝑛2(𝑚 +𝑀)

)

−1

[𝑔

2𝐿sin 𝜃𝑛 −

𝑚𝜔𝑛2 sin 𝜃𝑛 cos𝜃𝑛2(𝑚 +𝑀)

+(𝜇𝐹𝑣𝑛 − 𝜇𝐷𝜔𝑛) cos𝜃𝑛

2𝐿(𝑚 +𝑀)

−𝜇𝐷𝜔𝑛2𝑚𝐿

]

𝑑𝑣𝑛𝑑𝑡

= 𝑘𝑣1 = −(𝑚𝐿

𝑚 +𝑀)(𝑘𝜔1 cos𝜃𝑛 − 𝜔𝑛

2 sin 𝜃𝑛 −𝜇𝐷𝑚𝐿

𝜔𝑛 cos 𝜃𝑛 +𝜇𝐹𝑚𝐿

𝑣𝑛)

The equations can be reduced to the system with no external forces by setting 𝜇𝐷 = 𝜇𝐹 = 0.

Page 26: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

26

Appendix B – Simulation other two-body systems

The double-pendulum

The double-pendulum system is very commonly used in the study of classical mechanics and

chaos theory. A simple diagram is shown below.

Using Lagrangian mechanics, one obtains the following equations of motion [4]:

(𝑚1 +𝑚2)𝐿1�̈�1 +𝑚2𝐿2�̈�2 cos(𝜃1 − 𝜃2) + 𝑚2𝐿2�̇�2 sin(𝜃1 − 𝜃2) + 𝑔(𝑚1 +𝑚2) sin 𝜃1 = 0

𝑚2𝐿2�̈�2 +𝑚2𝐿1�̈�1 cos(𝜃1 − 𝜃2) − 𝑚2𝐿1�̇�12 sin(𝜃1 − 𝜃2) + 𝑚2𝑔 sin 𝜃2 = 0

Where both angles 𝜃1 and 𝜃2 are taken with respect to a vertical axis about their respective

centres of rotation. It follows that:

�̇�1 = 𝜔1; �̇�2 = 𝜔2

�̈�1 = �̇�1 = −(𝑚2𝐿2�̇�2 cos(𝜃1 − 𝜃2) + 𝑚2𝐿2𝜔2 sin(𝜃1 − 𝜃2) + 𝑔(𝑚1 +𝑚2) sin 𝜃1)

(𝑚1 +𝑚2)𝐿1

�̈�2 = �̇�2 = −𝐿1𝐿2(�̇�1 cos(𝜃1 − 𝜃2) − 𝜔1

2 sin(𝜃1 − 𝜃2) +𝑔

𝐿1sin 𝜃2)

Now, we need to uncouple these two equations by substituting �̇�2 into �̇�1:

�̇�1 =1

(𝑚1 +𝑚2)𝐿1(𝑚2𝐿1 (�̇�1 cos(𝜃1 − 𝜃2) − 𝜔1

2 sin(𝜃1 − 𝜃2) +𝑔

𝐿1sin 𝜃2) cos(𝜃1 − 𝜃2)

− 𝑚2𝐿2𝜔2 sin(𝜃1 − 𝜃2) − 𝑔(𝑚1 +𝑚2) sin 𝜃1)

Page 27: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

27

�̇�1 =𝑚2 cos

2(𝜃1 − 𝜃2)

(𝑚1 +𝑚2)�̇�1

+1

(𝑚1 +𝑚2)𝐿1(𝑚2𝐿1 (−𝜔1

2 sin(𝜃1 − 𝜃2) +𝑔

𝐿1sin 𝜃2) cos(𝜃1 − 𝜃2)

− 𝑚2𝐿2𝜔2 sin(𝜃1 − 𝜃2) − 𝑔(𝑚1 +𝑚2) sin 𝜃1)

∴ �̇�1 = [1 −𝑚2 cos

2(𝜃1 − 𝜃2)

(𝑚1 +𝑚2)]

−11

(𝑚1 +𝑚2)𝐿1(𝑚2𝐿1 (−𝜔1

2 sin(𝜃1 − 𝜃2)

+𝑔

𝐿1sin 𝜃2) cos(𝜃1 − 𝜃2) − 𝑚2𝐿2𝜔2 sin(𝜃1 − 𝜃2) − 𝑔(𝑚1 +𝑚2) sin 𝜃1)

Therefore the equations of motion for the system become:

�̇�1 = 𝜔1; �̇�2 = 𝜔2

�̇�1 = [1 −𝑚2 cos

2(𝜃1 − 𝜃2)

(𝑚1 +𝑚2)]

−11

(𝑚1 +𝑚2)𝐿1(𝑚2𝐿1 (−𝜔1

2 sin(𝜃1 − 𝜃2)

+𝑔

𝐿1sin 𝜃2) cos(𝜃1 − 𝜃2) − 𝑚2𝐿2𝜔2 sin(𝜃1 − 𝜃2) − 𝑔(𝑚1 +𝑚2) sin 𝜃1)

�̇�2 = −𝐿1𝐿2(�̇�1 cos(𝜃1 − 𝜃2) − 𝜔1

2 sin(𝜃1 − 𝜃2) +𝑔

𝐿1sin 𝜃2)

The damped double-pendulum

In order to analyse the system involving damping, one could use the Newtonian method to

derive the equations of motion. However, this would be extremely tedious and so the

Lagrangian method can be used by employing the Rayleigh dissipation function [3]:

𝐷 =1

2∑(𝜇𝑘�̇�𝑘

2)

𝑁

𝑘=0

Where 𝜇𝑘 are the damping coefficients. In the case of the double-pendulum, the function

becomes:

𝐷 =1

2(𝜇1�̇�1

2 + 𝜇2�̇�22)

To simplify our analysis, we will assume that 𝜇1 = 𝜇2 = 𝜇 as the only damping force acting

on the system would be air drag. Furthermore, adding this effect to the Euler-Lagrange

Equations yields:

𝑑

𝑑𝑡(𝑑𝐿

𝑑�̇�𝑘) =

𝑑𝐿

𝑑𝑞𝑘−𝑑𝐷

𝑑�̇�𝑘

This means that we can simply add this to the equations of motion we had originally:

(𝑚1 +𝑚2)𝐿1�̈�1 +𝑚2𝐿2�̈�2 cos(𝜃1 − 𝜃2) + 𝑚2𝐿2�̇�2 sin(𝜃1 − 𝜃2) + 𝑔(𝑚1 +𝑚2) sin 𝜃1+ 𝑘1�̇�1 = 0

𝑚2𝐿2�̈�2 +𝑚2𝐿1�̈�1 cos(𝜃1 − 𝜃2) − 𝑚2𝐿1�̇�12 sin(𝜃1 − 𝜃2) + 𝑚2𝑔 sin 𝜃2 + 𝑘2�̇�2 = 0

Page 28: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

28

Where 𝑘1 and 𝑘2 are constants that include the damping coefficient 𝜇 and a combination of

masses and lengths that may result from simplifying this equations at an earlier stage.

Now the equations of motion become:

�̇�1 = 𝜔1; �̇�2 = 𝜔2

�̈�1 = �̇�1

= −(𝑚2𝐿2�̇�2 cos(𝜃1 − 𝜃2) + 𝑚2𝐿2𝜔2 sin(𝜃1 − 𝜃2) + 𝑔(𝑚1 +𝑚2) sin 𝜃1 + 𝑘1�̇�1)

(𝑚1 +𝑚2)𝐿1

�̈�2 = �̇�2 = −𝐿1𝐿2(�̇�1 cos(𝜃1 − 𝜃2) − 𝜔1

2 sin(𝜃1 − 𝜃2) +𝑔

𝐿1sin 𝜃2 + 𝑘2�̇�2)

And substitution leads to:

�̇�1 = [1 −𝑚2 cos

2(𝜃1 − 𝜃2)

(𝑚1 +𝑚2)]

−11

(𝑚1 +𝑚2)𝐿1(𝑚2𝐿1 (−𝜔1

2 sin(𝜃1 − 𝜃2)

+𝑔

𝐿1sin 𝜃2) cos(𝜃1 − 𝜃2) − 𝑚2𝐿2𝜔2 sin(𝜃1 − 𝜃2) − 𝑔(𝑚1 +𝑚2) sin 𝜃1

− 𝑘1�̇�1)

Two coupled masses on springs

This problem is also quite common in classical mechanics. Consider a system in which two

masses are attached via springs, and which can only move horizontally. On both sides, there

are fixed walls. Also, one may include dampers in between to make the system more general,

as shown in the diagram below:

Where 𝑘 stands for spring constant, and 𝑏 stands for damping constant. The dampers are added

to simulate the effect of frictional forces on the masses. Simple Newtonian analysis leads to

the following equations of motion:

𝑚1�̈�1 = −𝑘1𝑥1 − 𝑏1�̇�1 − 𝑘2(𝑥1 − 𝑥2) − 𝑏2(�̇�1 − �̇�2)

𝑚2�̈�2 = −𝑘2(𝑥2 − 𝑥1) − 𝑏2(�̇�2 − �̇�1) − 𝑘3𝑥2 − 𝑏3�̇�2

This is a simple system to solve because there is no co-dependence of acceleration terms

between the two equations. One can make the following substitutions:

Page 29: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

29

�̇�1 = 𝑣1; �̇�2 = 𝑣2

�̈�1 = �̇�1 = −1

𝑚1

(𝑘1𝑥1 + 𝑏1𝑣1 + 𝑘2(𝑥1 − 𝑥2) + 𝑏2(𝑣1 − 𝑣2))

�̈�2 = �̇�2 = −1

𝑚2

(𝑘2(𝑥2 − 𝑥1) + 𝑏2(𝑣2 − 𝑣1) + 𝑘3𝑥2 + 𝑏3𝑣2)

Page 30: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

30

Appendix C – MATLAB Codes

C.1 – Inverted Pendulum Simulation

%**************************************************************************

% Program for solving nonlinear inverted pendulum system using the simple

% RK4 method for a system of 4 1st order equations.

%**************************************************************************

--- Additional Notes The following program can be used to solve any system of 2 nonlinear (or linear) 2nd order differential

equations. Simply adjust the initial conditions and parameters, and the expressions for the functions

fa, fo, fX and fv which are the k1 functions of the RK4 algorithm. The program also plots the phase

portraits for each of the nonlinear systems (derivative against its function), so the range of the plots

may also need to be adjusted to the specific problem. Every other part of the program can be left as

it stands.

Clear workspace This block simply clears everything in the workspace every time the program is run. It helps reduce

memory usage in the computer by MATLAB. It should be placed before everything else in the code.

clc %clear command prompt

clear %clear values

close all %close all figures, tables, diagrams, etc.

Define initial conditions, input parameters and constants All constants and initial values must be declared beforehand.

m = 1; % mass of the pendulum (kg)

M = 2; % mass of the cart (kg)

L = 1; % length of the pendulum (m)

g = 9.81; % gravitational constant (m/s^2)

t = 0; % initial time (s)

X = 0; % initial position of the cart (m)

a = 0.3; % initial angle of pendulum (rad)

v = 0; % initial velocity of the cart (m/s)

o = 0; % initial angular velocity of the pendulum (rad/s)

u_D = 0.5; % damping coefficient of drag force on pendulum (N.s/m)

u_F = 0.5; % damping coefficient of friction force on cart (N.s/m)

n = 10000; % number of steps in numerical approximation

h = 40/n; % time step-size in the numerical approximation

Define variables for animation (set as initial values) It is often convenient to use different variable names for the animation.

X0 = X;

t0 = t;

v0 = v;

a0 = a;

o0 = o;

Page 31: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

31

Define variables, vectors, matrices, etc This block creates the arrays where all the values for the different variables will be stored.

time = zeros(1,n);

position = zeros(1,n);

angle = zeros(1,n);

velocity = zeros(1,n);

omega = zeros(1,n);

Define functions for RK4 algorithm These are the functions corresponding to the expressions for the first and second derivatives

(equations of motion) that are used in the RK4 algorithm. It is important that they are written in the

correct order, as shown here, and that they are uncoupled beforehand (otherwise the program will

give an error “function < > is not defined”. The variable names in these functions should also be

different to the actual variables declared at the beginning of the code.

fa = @(tf,af,of,Xf,vf) of;

fo = @(tf,af,of,Xf,vf) (1-(m*cos(af)^2)/(2*(m+M)))^(-1)*(g/(2*L)*sin(af) - ...

(m*of^2*sin(af)*cos(af))/(2*(m+M)) + ...

(u_F*vf - u_D*of)*cos(af)/(2*L*(m+M)) - (u_D*of)/(2*m*L));

fX = @(tf,af,of,Xf,vf) vf;

fv = @(tf,af,of,Xf,vf) -(m*L)/(m+M)*(fo(tf,af,of,Xf,vf)*cos(af)- ...

of^2*sin(af) - (u_D*of*cos(af))/(m*L) + (u_F*vf)/(m*L));

% --- Note: if there are any coupled equations, uncouple them before typing

% in their expressions.

Initiate RK4 method This is the RK4 method as described in Appendix A. Each value of the arrays is updated with each

iteration, and all the “k” values for each of the functions is updated accordingly. Notice how declaring

functions outside the loop makes it easier to write the RK4 algorithm, by simply calling the functions

and inputting the desired variables. These “k” equations must also be written in order (all k1 values

first, then k2 values, and so forth). New variables “a”, “o”, etc. are updated at the end of the loop. The

words “tic” and “toc” surrounding the loop simply measure the amount of time taken to complete the

operation.

tic

for i = 1:n

% place values into vectors for plotting

time(1,i) = t;

angle(1,i) = a;

omega(1,i) = o;

position(1,i) = X;

velocity(1,i) = v;

% solve the system for the angular displacement equations

ka1 = fa(t, a, o, X, v);

ko1 = fo(t, a, o, X, v);

kX1 = fX(t, a, o, X, v);

kv1 = fv(t, a, o, X, v);

ka2 = fa(t + 0.5*h, a + 0.5*h*ka1, o + 0.5*h*ko1, X + 0.5*h*kX1, v + 0.5*h*kv1);

ko2 = fo(t + 0.5*h, a + 0.5*h*ka1, o + 0.5*h*ko1, X + 0.5*h*kX1, v + 0.5*h*kv1);

Page 32: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

32

kX2 = fX(t + 0.5*h, a + 0.5*h*ka1, o + 0.5*h*ko1, X + 0.5*h*kX1, v + 0.5*h*kv1);

kv2 = fv(t + 0.5*h, a + 0.5*h*ka1, o + 0.5*h*ko1, X + 0.5*h*kX1, v + 0.5*h*kv1);

ka3 = fa(t + 0.5*h, a + 0.5*h*ka2, o + 0.5*h*ko2, X + 0.5*h*kX2, v + 0.5*h*kv2);

ko3 = fo(t + 0.5*h, a + 0.5*h*ka2, o + 0.5*h*ko2, X + 0.5*h*kX2, v + 0.5*h*kv2);

kX3 = fX(t + 0.5*h, a + 0.5*h*ka2, o + 0.5*h*ko2, X + 0.5*h*kX2, v + 0.5*h*kv2);

kv3 = fv(t + 0.5*h, a + 0.5*h*ka2, o + 0.5*h*ko2, X + 0.5*h*kX2, v + 0.5*h*kv2);

ka4 = fa(t + h, a + h*ka3, o + h*ko3, X + h*kX3, v + h*kv3);

ko4 = fo(t + h, a + h*ka3, o + h*ko3, X + h*kX3, v + h*kv3);

kX4 = fX(t + h, a + h*ka3, o + h*ko3, X + h*kX3, v + h*kv3);

kv4 = fv(t + h, a + h*ka3, o + h*ko3, X + h*kX3, v + h*kv3);

% Update current values

a = a + h/6*(ka1 + 2*ka2 + 2*ka3 + ka4);

o = o + h/6*(ko1 + 2*ko2 + 2*ko3 + ko4);

X = X + h/6*(kX1 + 2*kX2 + 2*kX3 + kX4);

v = v + h/6*(kv1 + 2*kv2 + 2*kv3 + kv4);

t = t + h;

end

toc

Elapsed time is 2.150516 seconds.

Plot the resulting functions This block produces all 4 plots on the same figure by making use of the function “subplot(m,n,N)”,

where “m” is the number of rows, “n” the number of columns and “N” is the position of the plot with

respect to the others.

figure;

subplot(2,2,1)

plot(time,angle,'r'); xlabel('time (s)'); ylabel('angle (rad)');

subplot(2,2,2)

plot(time,position,'b'); xlabel('time (s)'); ylabel( ...

'cart displacement (m)');

subplot(2,2,3)

plot(time,omega,'r'); xlabel('time (seconds)'); ylabel(...

'angular velocity (rad/s)');

subplot(2,2,4)

plot(time,velocity,'b'); xlabel('time (seconds)'); ylabel(...

'cart velocity (m/s)');

Phase Portraits for nonlinear analysis This block produces the phase plots for positions and velocities.

figure;

plot(angle,position,'r');xlabel('pendulum angular displacement (rad)');

ylabel('cart displacement (m)');

figure;

plot(omega,velocity,'b');xlabel('pendulum angular velocity (rad/s)');

ylabel('cart velocity (m/s)');

Page 33: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

33

Create animated inverted pendulum system This final block creates the animation. The pivot point for the pendulum is chosen as the centre of the

cart, and it is convenient to express this as an array with two columns. Dimensions for the pendulum

and cart must also be declared here (or at the beginning of the code). For the rendering parameters,

the functions xlim and ylim define the domain and range of the x-y plane upon which the animation is

plotted. For convenience, one may choose the limits as the total length of the pendulum plus the cart

in either direction, or the minimum and maximum values in each direction (although this may often

make the animation look squeezed or contracted along the x-axis). The pendulum bob and cart are

defined using the function “rectangle()”, which establishes the position in terms of a 4 element vector

in the case of a rectangle, and a 3 element vector in the case of a circle (polar coordinates). Additionally,

the parameter “Curvature [1,1]” represents a full-circle. The pendulum rod is created using the

function “line()”.

The for loop updates the positions of the different shapes with each iteration by calling in each of the

values from the arrays that were generated from the RK4 loop. With each iteration, a new frame is

produced replacing the previous one. The number of steps in the numerical approximation will

determine the frame rate of the animation.

pivot = [X0 0]; % pivot position

r = 0.1; % radius of pendulum bob

pos = pivot + (L*[sin(a0) cos(a0)]); % Bob position

% Rendering parameters

figure;

axes = gca;

xlim(axes, [(pivot(1) - L) (pivot(1) + L)]);

ylim(axes, [(pivot(2) - L) (pivot(2) + L)]);

Bob = rectangle('Position', [(pos - r/2) r r], 'Curvature', [1,1], ...

'FaceColor', 'r'); % bob render

hold on

rod = line([pivot(1) pos(1)], [pivot(2) pos(2)]); % rod render

hold on

cart = rectangle('Position', [(pivot(1)-L/5) (pivot(2)-L/5) (2*L/5) (2*L/5)], ...

'FaceColor', 'b', 'EdgeColor', 'b'); % cart render

hold off

% Initiate animation

for time = 1:n % set same time scale as for solution to ODEs

drawnow;

X0 = position(1,time);

a0 = angle(1,time);

o0 = omega(1,time);

pivot = [X0 0];

pos = pivot + (L*[sin(a0) cos(a0)]);

set(Bob, 'Position',[(pos - r/2) r r]);

set(rod, 'XData', [pivot(1) pos(1)], 'YData', [pivot(2) pos(2)]);

set(cart, 'Position',[(pivot(1)-0.1*L) (pivot(2)-0.1*L) (0.2*L) (0.2*L)]);

end

Published with MATLAB® R2013b

Page 34: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

34

C.2 – Double Pendulum Simulation

%************************************************************************** % Program for solving nonlinear double pendulum system using the simple % RK4 method for a system of 4 1st order equations. %**************************************************************************

%% --- Additional Notes % The following program can be used to solve any system of 2 nonlinear (or % linear) 2nd order differential equations. Simply adjust the initial % conditions and parameters, and the expressions for the functions fa, fo, % fX and fv which are the k1 functions of the RK4 algorithm. The program % also plots the phase portraits for each of the nonlinear systems % (derivative against its function), so the range of the plots may also % need to be adjusted to the specific problem. Every other part of the % program can be left as it stands.

%% Clear workspace clc; %clear command prompt clear; %clear values close all; %close all figures, tables, diagrams, etc.

%% Define initial conditions, input parameters and constants m1 = 1; % mass of first pendulum m2 = 1; % mass of second pendulum L1 = 1; % length of first pendulum L2 = 1; % length of second pendulum g = 9.81; % gravitational constant t = 0; % initial time X = 4.5; % initial angle of second pendulum a = 2.5; % initial angle of first pendulum v = 0; % initial angular velocity of second pendulum o = 0; % initial angular velocity of first pendulum k1 = 0.5; % coefficient 1 k2 = 0.5; % coefficient 2 n = 10000; % number of points in numerical approximation h = 50/n; % step size in the numerical approximation

%% Define variables and initial conditions for animation X0 = X; t0 = t; v0 = v; a0 = a; o0 = o;

%% Define variables, vectors, matrices, etc time = zeros(1,n); position = zeros(1,n); angle = zeros(1,n); velocity = zeros(1,n); omega = zeros(1,n);

%% Define functions for RK4 algorithm fa = @(tf,af,of,Xf,vf) of; fX = @(tf,af,of,Xf,vf) vf; fo = @(tf,af,of,Xf,vf) (1-(m2*cos(af-Xf)^2)/(m1+m2))^(-

1)*1/(L1*m1+L1*m2)*(m2*L2*(-fa(tf,af,of,Xf,vf)^2*... sin(af - Xf) + g/L1*sin(Xf))*cos(af-Xf) -

m2*L2*fX(tf,af,of,Xf,vf)*sin(af-Xf) -... g*(m1+m2)*sin(af) - k1*fa(tf,af,of,Xf,vf));

Page 35: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

35

fv = @(tf,af,of,Xf,vf) -L1/L2*(fo(tf,af,of,Xf,vf)*cos(af-Xf)-... fa(tf,af,of,Xf,vf)^2*sin(af-Xf) + g/L1*sin(Xf) +

k2*fX(tf,af,of,Xf,vf)); % --- Note: if there are any coupled equations, uncouple them before typing % in their expressions.

%% Initiate RK4 method tic for i = 1:n % place values into vectors for plotting time(1,i) = t; angle(1,i) = a; omega(1,i) = o; position(1,i) = X; velocity(1,i) = v;

% solve the system for the angular displacement equations ka1 = fa(t, a, o, X, v); ko1 = fo(t, a, o, X, v); kX1 = fX(t, a, o, X, v); kv1 = fv(t, a, o, X, v); ka2 = fa(t + 0.5*h, a + 0.5*h*ka1, o + 0.5*h*ko1, X + 0.5*h*kX1, v +

0.5*h*kv1); ko2 = fo(t + 0.5*h, a + 0.5*h*ka1, o + 0.5*h*ko1, X + 0.5*h*kX1, v +

0.5*h*kv1); kX2 = fX(t + 0.5*h, a + 0.5*h*ka1, o + 0.5*h*ko1, X + 0.5*h*kX1, v +

0.5*h*kv1); kv2 = fv(t + 0.5*h, a + 0.5*h*ka1, o + 0.5*h*ko1, X + 0.5*h*kX1, v +

0.5*h*kv1); ka3 = fa(t + 0.5*h, a + 0.5*h*ka2, o + 0.5*h*ko2, X + 0.5*h*kX2, v +

0.5*h*kv2); ko3 = fo(t + 0.5*h, a + 0.5*h*ka2, o + 0.5*h*ko2, X + 0.5*h*kX2, v +

0.5*h*kv2); kX3 = fX(t + 0.5*h, a + 0.5*h*ka2, o + 0.5*h*ko2, X + 0.5*h*kX2, v +

0.5*h*kv2); kv3 = fv(t + 0.5*h, a + 0.5*h*ka2, o + 0.5*h*ko2, X + 0.5*h*kX2, v +

0.5*h*kv2); ka4 = fa(t + h, a + h*ka3, o + h*ko3, X + h*kX3, v + h*kv3); ko4 = fo(t + h, a + h*ka3, o + h*ko3, X + h*kX3, v + h*kv3); kX4 = fX(t + h, a + h*ka3, o + h*ko3, X + h*kX3, v + h*kv3); kv4 = fv(t + h, a + h*ka3, o + h*ko3, X + h*kX3, v + h*kv3);

% Update current values a = a + h/6*(ka1 + 2*ka2 + 2*ka3 + ka4); o = o + h/6*(ko1 + 2*ko2 + 2*ko3 + ko4); X = X + h/6*(kX1 + 2*kX2 + 2*kX3 + kX4); v = v + h/6*(kv1 + 2*kv2 + 2*kv3 + kv4); t = t + h; end toc

%% Plot the resulting functions plot(time,angle,'r'); xlabel('time (s)'); ylabel('angle of first pendulum

(rad)');figure;

plot(time,position,'b'); xlabel('time (s)'); ylabel( ... 'angle of second pendulum (rad)');figure;

plot(time,omega,'r'); xlabel('time (seconds)'); ylabel(... 'angular velocity of first pendulum (rad/s)');figure;

Page 36: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

36

plot(time,velocity,'b'); xlabel('time (seconds)'); ylabel(... 'angular velocity of second pendulum (rad/s)');

%% Create animation % Define pendulum pivot = [0 0]; % pivot position r = 0.1; % radius of pendulum bob r2 = 0.1; % radius of second pendulum bob

pos = pivot - (L1*[sin(a0) cos(a0)]); % Bob 1 position pos2 = pos - (L2*[sin(X0) cos(X0)]); % Bob 2 position

% --- Rendering parameters % set scale on x-y plane for animation figure; axes = gca; xlim(axes, [-(L1 + L2 + r + r2) (L1 + L2 + r + r2)]); ylim(axes, [-(L1 + L2 + r + r2) (L1 + L2 + r + r2)]);

% create shapes for pendulum system Bob = rectangle('Position', [(pos - r/2) r r], 'Curvature', [1,1], ... 'FaceColor', 'r'); hold on rod = line([pivot(1) pos(1)], [pivot(2) pos(2)]); hold on Bob2 = rectangle('Position', [(pos2 - r2/2) r2 r2], ... 'Curvature', [1,1], 'FaceColor', 'b'); hold on rod2 = line([pos(1) pos2(1)], [pos(2) pos2(2)]); hold off

% --- Initiate animation for time1 = 1:n % set same time scale as for solution to ODEs drawnow; % draw elements X0 = position(1,time1); a0 = angle(1,time1);

% update position for both pendulums pos = pivot - (L1*[sin(a0) cos(a0)]); pos2 = pos - (L2*[sin(X0) cos(X0)]); set(Bob, 'Position',[(pos - r/2) r r]); set(Bob2, 'Position', [(pos2 - r2/2) r2 r2]); set(rod, 'XData', [pivot(1) pos(1)], 'YData', [pivot(2) pos(2)]); set(rod2, 'XData', [pos(1) pos2(1)], 'YData', [pos(2) pos2(2)]); end

C.3 – Coupled Harmonic Oscillator Simulation

%************************************************************************** % Program for solving coupled harmonic oscillator system using the simple % RK4 method for a system of 4 1st order equations. %**************************************************************************

%% --- Additional Notes % The following program can be used to solve any system of 2 nonlinear (or % linear) 2nd order differential equations. Simply adjust the initial % conditions and parameters, and the expressions for the functions fa, fo, % fX and fv which are the k1 functions of the RK4 algorithm. The program

Page 37: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

37

% also plots the phase portraits for each of the nonlinear systems % (derivative against its function), so the range of the plots may also % need to be adjusted to the specific problem. Every other part of the % program can be left as it stands.

%% Clear workspace clc %clear command prompt clear %clear values close all %close all figures, tables, diagrams, etc.

%% Define initial conditions, input parameters and constants m1 = 1; % mass 1 m2 = 2; % mass 2 g = 9.81; % gravitational constant t = 0; % initial time L = 1; % distance between two masses (length of relaxed spring) X = 0.5; % initial position of mass 2 a = 0.5; % initial position of mass 1 v = 0; % initial velocity of mass 2 o = 0; % initial velocity of mass 1 b1 = 0.0; % damping coefficient for damper 1 b2 = 0.0; % damping coefficient for damper 2 b3 = 0.0; % damping coefficient for damper 3 S1 = 0.2; % spring constant 1 S2 = 0.2; % spring constant 2 S3 = 0.2; % spring constant 3 n = 1000; % number of points in numerical approximation h = 50/n; % step size in the numerical approximation

%% Define variables and initial conditions for animation X0 = X; a0 = a; t0 = t; v0 = v; o0 = o;

%% Define variables, vectors, matrices, etc time = zeros(1,n); position = zeros(1,n); angle = zeros(1,n); velocity = zeros(1,n); omega = zeros(1,n);

%% Define functions for RK4 algorithm fa = @(tf,af,of,Xf,vf) of; fX = @(tf,af,of,Xf,vf) vf; fo = @(tf,af,of,Xf,vf) -1/m1*(S1*af+b1*fa(tf,af,of,Xf,vf)+S2*(af-Xf)+... b2*(fa(tf,af,of,Xf,vf)-fX(tf,af,of,Xf,vf))); fv = @(tf,af,of,Xf,vf) -1/m2*(S3*Xf+b3*fo(tf,af,of,Xf,vf)+S2*(Xf-af)+... b2*(fX(tf,af,of,Xf,vf)-fa(tf,af,of,Xf,vf))); % --- Note: if there are any coupled equations, uncouple them before typing % in their expressions.

%% Initiate RK4 method tic for i = 1:n % place values into vectors for plotting time(1,i) = t; angle(1,i) = a; omega(1,i) = o;

Page 38: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

38

position(1,i) = X; velocity(1,i) = v;

% solve the system for the angular displacement equations ka1 = fa(t, a, o, X, v); ko1 = fo(t, a, o, X, v); kX1 = fX(t, a, o, X, v); kv1 = fv(t, a, o, X, v); ka2 = fa(t + 0.5*h, a + 0.5*h*ka1, o + 0.5*h*ko1, X + 0.5*h*kX1, v +

0.5*h*kv1); ko2 = fo(t + 0.5*h, a + 0.5*h*ka1, o + 0.5*h*ko1, X + 0.5*h*kX1, v +

0.5*h*kv1); kX2 = fX(t + 0.5*h, a + 0.5*h*ka1, o + 0.5*h*ko1, X + 0.5*h*kX1, v +

0.5*h*kv1); kv2 = fv(t + 0.5*h, a + 0.5*h*ka1, o + 0.5*h*ko1, X + 0.5*h*kX1, v +

0.5*h*kv1); ka3 = fa(t + 0.5*h, a + 0.5*h*ka2, o + 0.5*h*ko2, X + 0.5*h*kX2, v +

0.5*h*kv2); ko3 = fo(t + 0.5*h, a + 0.5*h*ka2, o + 0.5*h*ko2, X + 0.5*h*kX2, v +

0.5*h*kv2); kX3 = fX(t + 0.5*h, a + 0.5*h*ka2, o + 0.5*h*ko2, X + 0.5*h*kX2, v +

0.5*h*kv2); kv3 = fv(t + 0.5*h, a + 0.5*h*ka2, o + 0.5*h*ko2, X + 0.5*h*kX2, v +

0.5*h*kv2); ka4 = fa(t + h, a + h*ka3, o + h*ko3, X + h*kX3, v + h*kv3); ko4 = fo(t + h, a + h*ka3, o + h*ko3, X + h*kX3, v + h*kv3); kX4 = fX(t + h, a + h*ka3, o + h*ko3, X + h*kX3, v + h*kv3); kv4 = fv(t + h, a + h*ka3, o + h*ko3, X + h*kX3, v + h*kv3);

% Update current values a = a + h/6*(ka1 + 2*ka2 + 2*ka3 + ka4); o = o + h/6*(ko1 + 2*ko2 + 2*ko3 + ko4); X = X + h/6*(kX1 + 2*kX2 + 2*kX3 + kX4); v = v + h/6*(kv1 + 2*kv2 + 2*kv3 + kv4); t = t + h; end toc

%% Plot the resulting functions plot(time,angle,'r'); xlabel('time (s)'); ylabel('angle (rad)');figure;

plot(time,position,'b'); xlabel('time (s)'); ylabel( ... 'cart displacement (m)');figure;

plot(time,omega,'r'); xlabel('time (seconds)'); ylabel(... 'angular velocity (rad/s)');figure;

plot(time,velocity,'b'); xlabel('time (seconds)'); ylabel(... 'cart velocity (m/s)');

%% Create animated inverted pendulum system %% Create animated inverted pendulum system % Define pendulum r = 0.3; % size of box

pos1 = [(L+a0) 0]; % mass 1 position pos2 = [(2*L+X0) 0]; % mass 2 position

% --- Rendering parameters

Page 39: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

39

% set scale on x-y plane for animation figure; axes = gca; xlim(axes, [0 (3*L)]); ylim(axes, [-L L]);

% create shapes mass1 = rectangle('Position', [(pos1(1) - r/2) (pos1(2) - r/2) r r], ... 'FaceColor', 'r', 'EdgeColor', 'r'); hold on mass2 = rectangle('Position', [(pos2(1) - r/2) (pos2(2) - r/2) r r], ... 'FaceColor', 'b', 'EdgeColor', 'b'); hold off

% --- Initiate animation for time = 1:n % set same time scale as for solution to ODEs drawnow; % draw elements X0 = position(1,time); a0 = angle(1,time); o0 = omega(1,time);

pos1 = [(L+a0) 0]; % mass 1 position pos2 = [(2*L+X0) 0]; % mass 2 position % update position of bob, rod and cart set(mass1, 'Position',[(pos1(1) - r/2) (pos1(2) - r/2) r r]); set(mass2, 'Position',[(pos2(1) - r/2) (pos2(2) - r/2) r r]); end

C.4. Simple pendulum simulation and error analysis

%************************************************************************** % Program for solving linear simple pendulum and comparing numerical to % analytical solution %**************************************************************************

%% Define initial conditions, input parameters and constants m = 1; % mass of the pendulum (kg) L = 1; % length of the pendulum (m) g = 9.81; % gravitational constant (m/s^2) a = 0.10; % initial angle of pendulum (rad) o = 0; % initial angular velocity of the pendulum (rad/s)

%% Define functions for RK4 algorithm fa = @(tf,af,of) of; fo = @(tf,af,of) -g/L*af;

%% Define arrays to contain error values steps = zeros(1,5); error = zeros(1,5);

%% Initiate RK4 method for j = 2:6 n = 10^j; % number of steps h = 5/n; % time step-size in the numerical approximation global_error = 0; % sets initial global error to zero for each loop

%% Define variables, vectors, matrices, etc t = 0;

Page 40: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

40

a = 0.1; o = 0; time = zeros(1,n); angle = zeros(1,n); omega = zeros(1,n);

%% Analytical solution a_1 = @(tf) a*cos(sqrt(g/L)*tf); a_analytic = zeros(1,n); difference = zeros(1,n);

for i = 1:n % place values into vectors for plotting time(1,i) = t; angle(1,i) = a; omega(1,i) = o;

% solve the system for the angular displacement equations ka1 = fa(t, a, o); ko1 = fo(t, a, o); ka2 = fa(t + 0.5*h, a + 0.5*h*ka1, o + 0.5*h*ko1); ko2 = fo(t + 0.5*h, a + 0.5*h*ka1, o + 0.5*h*ko1); ka3 = fa(t + 0.5*h, a + 0.5*h*ka2, o + 0.5*h*ko2); ko3 = fo(t + 0.5*h, a + 0.5*h*ka2, o + 0.5*h*ko2); ka4 = fa(t + h, a + h*ka3, o + h*ko3); ko4 = fo(t + h, a + h*ka3, o + h*ko3);

% Update current values a = a + h/6*(ka1 + 2*ka2 + 2*ka3 + ka4); o = o + h/6*(ko1 + 2*ko2 + 2*ko3 + ko4); t = t + h; a_analytic(1,i) = a_1(time(1,i)); difference(1,i) = abs(a_analytic(1,i) - angle(1,i)); global_error = global_error + difference(1,i); end steps(1,j-1) = h; error(1,j-1) = global_error;

end

%% Plot the resulting functions figure; plot(time,angle,'r'); xlabel('time (s)'); ylabel('angle (rad)');

figure; plot(time,a_analytic,'g'); xlabel('time (seconds)'); ylabel(... 'angle (rad)');

%% Error analysis and validation figure; plot(steps,error,'b'); xlabel('step-size'); ylabel('global error (rad)');

Page 41: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

41

Appendix D – Activity Log and Project Management

The project was completed over a period of 12 weeks. A short description of all changes and

improvements on a weekly basis is presented in this appendix.

Week Date Description

1 21/03/2016 In this week I looked into the basic theory behind discretisation of

differential equations, numerical differentiation techniques, Taylor

series expansions, and error estimation. At this point I also started

getting more acquainted with the MATLAB syntax and how to

perform basic operations, such as declaring functions and variables,

using for and while loops, creating and modifying arrays, and more.

2 28/03/2016 During this week I started working on developing a MATLAB code

that utilised the Euler method to solve a simple pendulum system.

First, I implemented the code on the linearized version of the equation

by assuming only a small initial angle, and compared it to the

analytical solution which I derived based on fixed parameters. The

program performed relatively well, but I had a little bit of difficulty

understanding how to transform a second order differential equation

into a system of first order ODEs. Luckily I found the textbook

“Introductory Computational Physics” by Klein and Godunov, which

had a very simple and concise explanation with some useful examples,

and this helped me begin planning my main project.

3 04/04/2016 During this week I expanded my code from the previous week to solve

the nonlinear differential equation for a simple pendulum. At this

point I began looking into other numerical methods that would

provide better approximations and stability. When testing the code I

encountered a few problems with it as was not producing the expected

results. I had to perform some changes and in the end, after testing a

simple RK4 algorithm which I found from the textbook, I decided this

was a much better choice for the inverted pendulum project.

4 11/04/2016 In this week I improved the code slightly, and wrote a report on the

Euler method for modelling the simple pendulum in both the nonlinear

and linearized cases. I also started looking in more depth into the

dynamics of inverted pendulum systems. At this point, the idea of my

project was to collaborate with Tristan Walsh to develop a code that

would simulate the system and also generate a function that would

allow the pendulum to remain upright. This idea was borrowed from

control theory, as it is a widely explored example.

5 18/04/2016 In this week I began deriving the equations of motion for the inverted

pendulum of system. I took into account a model in which the

pendulum was free to swing 360o and the cart was limited to moving

horizontally to the sides. The method of choice was the Lagrangian

method as I had fresh knowledge from previous year subjects. This

part was particularly tedious as the inverted pendulum proved to be a

challenging system to analyse. In order to verify my solutions were

correct, I used the Newtonian method of derivation in parallel with the

Lagrangian to ensure that I obtained the exact same solutions. At this

point I did not do any programming, but rather focused on deriving all

the master equations I would need for the program, including those

Page 42: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

42

that took the effects of air drag and friction on the system into

consideration.

6 25/04/2016 During this week Tristan and I decided to focus on different projects,

and I stayed with the inverted pendulum system. I began writing an

algorithm by hand, using pseudo-code, arrays and loops to get a better

idea of how I would make the real code work when it came time to

writing it. Initially I did some research trying to find implementations

of the RK4 algorithm to systems of second order differential

equations, but had a lot of trouble finding any. At this point I realised

there was a gap in the literature, or at least a lack of applications of

the RK4 for systems of differential equations as those normally found

in classical mechanics.

7 02/05/2016 This week I began writing the code for the inverted pendulum system.

I also started the process of reviewing projects from my peers and

providing a few comments on how to improve their codes or

simulations. I had some trouble at first as I was not aware that the RK4

algorithm does not work unless you define each variable to be found

as a function of all other variables and time. For instance, a system of

two second order differential equations needs to be broken down into

4 first order equations, and each of those derivatives needs to be

declared as a function of 5 variables including time, and first and

second derivatives from each of the differential equations. After

identifying this problem, I rewrote the algorithm in my code and got

it working for the first time. By this point it only produced a few

graphs showing positions and velocities of each mass with respect to

time.

8 09/05/2016 This week I focused mainly on improving the structure of the code. I

also added a small animation feature to it. The animation part was a

bit challenging as I could not find a lot of examples or MATLAB

documentation online, so there was a lot of trial and error that went

into the process of testing it. I also began deriving equations of motion

for a double-pendulum and coupled harmonic oscillator.

9 16/05/2016 This week I decided to extend the capabilities of my code by using it

to simulate other two-body systems: the double-pendulum and the

coupled harmonic oscillator. I found that I only needed to change the

input parameters slightly and the differential equations that were fed

into the RK4 algorithm, as well as changing some of the shapes used

in the animation. But other than that, the code was easy to implement

and setting up the different problems only took about 15 – 20 minutes

each. Both animations performed as expected and the result was quite

satisfying, as now I could implement my code to virtually any two-

body system, which was more than I originally planned to achieve

with this project. I received some feedback from Angus Gentle and

Mathew Arnold, so I started making improvements to my program

and report.

10 23/05/2016 This week I focused on more peer reviews and adding all missing

sections to the report and documentation. I also started looking into

other ways to validate my code and perform error analysis. I decided

to use phase portraits as they are quite common in nonlinear dynamics

to perform a qualitative analysis of the solutions, and compared them

Page 43: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

43

with assumptions based on expected behaviour of the system, which

in itself consisted of conservation principles (e.g. if there is friction in

the cart then the oscillations should decay quite rapidly in proportion

to the magnitude of the damping coefficient). I also investigated the

effect of step-size in the RK4 approximation, and used this to explore

how fast the error converged for decreasing step size.

11 30/05/2016 On this week I looked more into numerical validation of the RK4

method and my results. I looked into phase portraits and Poincare

sections, however most of the resources I found on the latter were not

very explanatory or intuitive, so upon finding difficulty in

understanding how to implement them in MATLAB I decided to focus

mainly on phase portraits as a qualitative analysis tool of nonlinear

dynamics, and also plotting the global error against step-size for a

simpler problem: the simple linearized pendulum, for which I wrote a

separate code.

12 06/06/2016 This week I focused on finishing the report and making a few last

improvements to the code. As I did not have enough time, I did not

explore other options for making the code more user-friendly (e.g.

adding a GUI or turning the differential equations into function inputs

that could be specified by the user so the program automatically

adjusted to the specific problem without having to change the code

manually), but these are some areas I would have liked to look further

into. All in all, the project was very interesting and taught me not only

how to write efficient code in MATLAB, but also how to approach

problem-solving from different perspectives.

Page 44: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

44

Appendix E – Review of other Projects

E.4. Tristan Walsh (11196108): Modelling of a simple spring and mass system using MATLAB

Criteria Grade Comments and Feedback

Overall D The report is of very high quality, and includes very detailed information, covering all the criteria to a

satisfactory standard. Results and analysis are substantial and are clearly linked to the aim and motivation

of the project. The code is well documented and is flexible to a certain degree, although still limited to

second order differential equations. The overall structure can be improved (see background explained

section), and a few improvements to the layout can be made: make the text justified, re-organize cover page

so that the abstract does not look out of place, and ensure that more references are included and that they

are cited in text, especially when equations are presented.

Aim stated HD The aim is very clear and supported by relevant graphs, well-drawn and presented. No improvements

required.

Motivation HD The motivation behind the project is explained very concisely and is demonstrated throughout the analysis

of the results.

Background explained C Parameters and master equations are clearly outlined. Limitations and results clearly discussed. The

referencing can be significantly improved, however. Add more references, and use the Harvard style to

make it more formal. Use in-text citations wherever possible when using diagrams or equations, so that it

can be known to the reader where these came from (unless they were derived by the author himself). I

would suggest to include all textbooks or resources you may have taken the equations from, and make

reference to them throughout the report at least once, so that it improves the grade for this criteria.

Additionally, you could re-arrange some of the sections in the report by moving all equation derivations

into an appendix (before the code itself), so that it does not detract from the main investigation.

Method developed

(flexible code)

D Modular form implemented, variables clearly explained. Efficient use of headings and subheadings,

relatively easy to read and follow. However, the overall presentation of the code could be improved (check

grammar, there are some typesetting errors in it).

Method documented HD Code is properly documented and explained.

Method validated HD Excellent use of graphs and figures to compare solutions and their accuracy based on the error between the

numerical and analytical solutions.

Results presented

(graphs, presentation,

tables, etc.)

D All graphs are properly labelled and well-presented. However, not a lot of innovation in the presentation of

data. Perhaps adding an animation feature to the code that shows how the system behaves could improve

the overall visualisation of the dynamics explored in the project.

Page 45: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

45

Problem explored HD Overall, the problem explored is very succinct and all the essential parameters and information is presented

and discussed throughout. Documentation is very good, and include limitations, implications and

suggestions for future improvement.

Project management

and collaborative

review

P There is evidence of project management, although the activity log is quite short and could use a more

detailed description of what was achieved each week in the lead-up to the final result. For instance, you

could use longer sentences or short paragraphs to explain the changes and/or modifications that were done.

Also, the collaborative review is very vague and does not show evidence of the author reviewing other

projects or making suggestions to colleagues. Adding more information to these two sections could increase

the overall grade.

E.2. Blake Regan (11970579): Projectile motion with drag

Criteria Grade Comments and Feedback

Overall D Overall very good report and the exploration of the problem was very detailed, and discusses the

applicability of the outcomes to a real-life scenario. The structure and layout (mainly tidiness and

captioning of graphs) is the one thing that needs to be improved according to the recommendations for each

criteria.

Aim stated D Aim is properly stated, though brief.

Motivation HD Motivation properly explained and demonstrates applicability of the project to a real-life scenario, which

is ideal with computational simulations.

Background explained HD Background information is substantial and discussed in detail, properly referenced and use of in-text

citations is adequate and efficient.

Method developed

(flexible code)

D Code is easy to read and understand, but is limited to just the problem described in the aim.

Method validated C The method is lacking error analysis and validation of the results. It might be required to include

convergence of the solutions with variation in step-size as well as a concise discussion on the performance

of the code ( a comparison of solutions is already provided, but it needs to be more quantitative and look at

different cases using different step sizes).

Method documented D Method and code are well-documented, but adding more comments to the code (e.g. brief explanations of

some of the functions, loops, structures, etc.) could improve how well it is understood by the reader.

Page 46: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

46

Results presented

(graphs, presentation,

tables, etc.)

C Graphs are properly labelled and well-presented, but the layout can be improved. Figures and diagrams

should be centred and captioned if they appear in the main body of the report (if they only appear in the

appendix then this is not necessary). Some of the screenshots taken from the output of the program contain

too much grey space around them, and some of the text relevant to the graphs is not properly placed.

Another thing is: whenever variables or coefficients are included in-text, they should be properly typed

using the equation toolbox on Word, just to maintain consistency and make sure that subscripts and

superscripts are clear (e.g. “Co” is not the same as 𝐶0). The table from experiment 2 should be included in

the appendix for better convenience (since it is just numbers) and properly structured (rather than using a

screenshot, copy the table from Excel and modify font size and type to match the rest of the report), and

use Landscape page orientation for this so the table fits properly. Another note: make text justified to

improve aesthetics.

Problem explored D Parameters are clearly identified and used throughout the report.

Project management

and collaborative

review

HD There is sound evidence of collaborative review with peers, and a good activity log of all modifications and

milestones achieved in the lead-up to the final product.

E.3. Liam Martin (12050783): kinetic rate modelling of non-equilibrium Langmuir isotherm absorption process using Runge-Kutta

Methods

Criteria Grade Comments and Feedback

Overall C The project is looking good and is quite original, I particularly like the exploration of the Runge-Kutta

methods with applications in chemistry, and the code is very clean, concise and well-structured. However,

as of yet the report is incomplete so it is hard for me to judge the overall quality based on the little

information that is available at present. What I can recommend however is to do a small re-structuring of

the report: place all equation derivations as an appendix at the end (except for the Runge-Kutta algorithm,

this should remain where it is), before the MATLAB script, and only put the final equations in the body of

the report (e.g. the ones you solved with the code). The other thing would be general house-keeping with

the code: in-line comments should be aligned within sections (as these can be thought of as dot points, see

example attached) as this improves readability. The loops, variable definitions and RK4 algorithm are all

very well-presented and there is a good amount of short commentary in the code that aids the reader identify

the uses of each block. The rest of the report needs a lot more explanations and substance, but it is on the

right track.

Page 47: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

47

You need to also include at least 1 page explaining the aim of the project, coupled with the motivation

behind it (e.g. reasons why you decided to do it and whether it is something that has not been done before,

etc.). Additionally, include at the end of the appendix the following two things: your weekly activity log

and reviews you made to your peers.

Aim stated - NA

Motivation - NA

Background explained C Background information is sufficient but could use more details, and in-text citations should also be added

(especially for equations and algorithms like Runge-Kutta) and make use of the references provided. No

list of references is provided so far, but Harvard style referencing should be used (also it would be

convenient to use numbered citations in-text as opposed to full-length citations).

Method developed

(flexible code)

HD The code is of outstanding quality and is very pleasant to read. The only minor thing that could be changed

is the alignment of in-line comments (they should be aligned as dot points within each block of code),

leaving enough blank space between the actual code and the comment so they don’t become clustered.

Also, the numeric output seems to be overlaid because the resolution is not self-adjusting, so maybe this is

something you could look into so that when someone runs the program on a different computer the aspect

ratio remains constant (see screenshot attached).

Method documented - NA

Method validated C On good track by comparing solutions with respect to step-size using the same input parameters, but it still

needs more explanation. In the discussion, you could also include

Results presented

(graphs, presentation,

tables, etc.)

C No graphs provided as of yet, but the aesthetics of the tables could be improved by using a different format

(instead of the alternating grey and white rows, use plain white, and make sure you add a caption on top of

each table describing what it contains). I can see from the output of the program that the graphs produced

are very neat and clearly labelled, so make sure you also caption them in the report once you add them in.

Problem explored - NA

Project management

and collaborative

review

- NA

Page 48: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

48

E.4. Luke Weatherstone (): three-dimensional Brownian motion in water

Criteria Grade Comments and Feedback

Overall D Overall this is a very good report and the program is functional and useful for analysing the dynamics of

Brownian particles in water. The little 3D animation is also a good feature. I think some improvements can

be done in terms of report structure (see below) and perhaps adding more content to it. For instance, the

validation section is lacking in comparison to the others, so perhaps you could focus on that. Nevertheless,

an interesting project and a good exploration of the problem.

Aim stated C Aim is clearly stated, although it could use some more substance in it.

Motivation D Motivation clearly explained and applicability of the simulation to real physical scenarios is also stated.

Background explained D Background theory is very thorough and well explained. The only improvement might be using more in-

text references, especially with respect to a lot of the equations used. Another comment is: perhaps you

could relocate much of the bulk of the equations from the main body into an appendix, and keeping only

the main equations in the body.

Method developed

(flexible code)

D The code is very neat and easy to navigate through, parameters and variables are well-specified. The

simulations are good, but perhaps more stuff could be added to the program (e.g. more graphs showing

other properties of the system of particles). Although Brownian motion is hard to simulate, there are more

things you could do with the program as Wiener processes are applicable to a wide range of physical

phenomena (e.g. look into Ornstein-Uhlenbeck processes and how they relate to the problem of damping

in Brownian particles, this might provide an improvement on your current model using classical drag /

friction force equations by taking advantage of the normal distribution).

Method documented HD The method and code are very well documented in modular form, all sections clearly explained. However,

maybe this is something you could place in the appendix rather than the main body of the report as it is

quite long and detracts a bit from the discussion and analysis of the results.

Method validated C The results are yet to be validated fully, for instance by looking at the effect of step size in the accuracy of

the simulation, given you have a theoretical solution to compare it to, and discussing this into more detail.

Results presented

(graphs, presentation,

tables, etc.)

D Graphs are properly labelled and of good quality. However, there are no captions on most of them (both

graphs and tables), so you should add this to improve overall quality of the report.

Problem explored D Overall the problem explored is of a certain difficulty and does demonstrate a good understanding of the

physical and mathematical principles behind Brownian motion.

Page 49: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

49

Project management

and collaborative

review

C The activity log-book is sufficiently detailed and demonstrates consistent improvement of the simulation

throughout the semester. There is evidence of various reviews done by peers, but the use of screenshots to

show the comments provided back and forth is not very effective when presented in this report format.

What I would suggest is take the comments out and organise them better, perhaps in the form of a table, so

they are more readable. Also, reviews done by you on other people’s projects need to be added to the report.

E.5. Reuben Puyol (11042912): projectile motion and air resistance and its effect on range

Criteria Grade Comments and Feedback

Overall D The report has an excellent structure and uses a professional format, including all necessary information

without overwhelming the reader with too many details. Some improvements could be made by making

the code and graphs a little neater (see comments below). Also, you could explore other numerical methods

like Runge-Kutta to increase the depth of your investigation.

Aim stated C Aim is stated, but you could elaborate more on this.

Motivation C Motivation is outlined and explained to a certain degree, but it could use more context. For instance, you

could mention the applicability of this in a real scenario.

Background explained D All relevant equations are clearly explained, and so is the background theory of the problem being

investigated.

Method developed

(flexible code)

D The code is very well-written, but focuses mostly on solving one problem at a time. Perhaps it would be

beneficial to incorporate the code and perhaps reduce its length by making use of less functions or

structures. Also, you could align the in-line comments so that it looks tidier.

Method documented D Methods are well documented. The code is properly structured and has good readability.

Method validated HD Methods are properly validated and there is a substantial amount of discussion analysing the main aspects

of the variation of error and the importance of selecting the most suitable step-size. A comparison is also

performed with analytical solutions and there are plenty of graphs to illustrate the differences.

Results presented

(graphs, presentation,

tables, etc.)

D Graphs are properly labelled, and have captions containing brief but concise descriptions of the phenomena

they represent. However, their aesthetics can be improved by getting rid of the grey background around the

edges (you can do this by using the publishing tool in MATLAB, which outputs the graphs in a neater way).

Problem explored C The project is very well documented and demonstrates a good understanding of programming and applying

classical mechanics to the simulation of projectile motion with air-resistance. However, the program is

limited to the use of the Euler method, which is quite simple and not very stable for certain cases. Perhaps

Page 50: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

50

you could expand on this by exploring the Runge-Kutta method and implementing it in your code, and then

comparing the two methods to see how they perform on different cases.

Project management

and collaborative

review

P There is some evidence of peer reviews though not very substantial, and no activity log-book showing

process of completion for the project.

Page 51: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

51

Appendix F – Reviews from peers

F.1. Review by Blake Regan

Criteria Grade Comments and Feedback

Overall HD Extremely professional and comprehensive, with interesting mathematics and obvious care taken to work

Aim stated D The Aim is stated in detail, but in a more round about way, it is held within the introduction section, and is not

explicitly stated directly, but is understood thoroughly.

Motivation C The Motivation is clearly to show the response of the Mathematical model to extreme circumstances, however as

part of the motivation criteria is engagement with society, I can find no evidence of this.

Background

explained

HD Background is explained fully and thoroughly, yet still manages to be concise. This is an impressive section

Method developed

(flexible code)

HD The code is adaptable from standard experiments to latter more difficult experiments, As well as the code being

easily readable through extensive use of comments.

Method validated C The method validation is brief, and in need of graphical backup, or data backup. You have stated what the source

error is, but it has yet to be shown.

You have proven without question the validity of your maths and methods, I would just like to see proof of code.

Results presented

(graphs,

presentation, tables,

etc.)

HD Again, much as in other sections related to presentation, it is quite flawless.

Problem explored HD The problem has been explored in great depth, with many tests and corresponding data sets and tables to show how

the code and results react to many circumstances

Project management

and collaborative

review

C The reviews you have given are professional and honest. However I did not see any evidence of a Log or the

development of the code. As this was a comment made to me by Angus, it would be worth adding if possible

Page 52: Oscar Nieves (11710858) Computational Physics Project - Inverted Pendulum

52

F.2. Review by Tristan Walsh

Criteria Grade Comments and Feedback

Overall

Aim stated HD The aim is clearly stated and the background theory/ problem is described in detail making use of diagrams.

Motivation D The introduction of the paper provides a detailed description of the motivation behind the work. Some

references could be made to examples of other studies that have done work upon the inverted pendulum

problem. Also, some comments could be made as to why exactly it is useful to model the full dynamics of

the system.

Background explained D The background theory behind the algorithms used and the inverted pendulum problem itself is described

in detail. Some references could be included to specify where the information on each algorithm originated

from.

Method developed

(flexible code)

D The code is well implemented, clear, and customisable to a variety of different problems, as demonstrated.

It could be modularised to include the RK4 function/ derivative definitions and other useful code snippets

in separate files, so that these can be easily reused in other situations without having to copy and paste and

manually change the values they take as parameters.

Method documented D The code documentation provides a clear description how to use the code, and the reasoning behind it.

Method validated ~ At the time of viewing, this section appears to be incomplete, but the method that will be used to validate

the code has been stated. It appears to be a satisfactory validation method given the difficulty of obtaining

an analytical solution for these types of problems.

Results presented

(graphs, presentation,

tables, etc.)

D The results are presented clearly and explained.

Problem explored HD The inverted pendulum problem has been explored well with a variety of different parameter combinations

presented and their affects upon the results discussed.

The code has also been applied to a large variety of other problems.

Project management

and collaborative

review

~ At the time of viewing the project management section was not completed.

Project reviews were also not complete, yet the template set out (used in this review itself) helps assess

each section of the report well.