You are on page 1of 25

Runge‐Kutta

Numerical Methods used in Evaluation of


Differential Equations
 
Daniel Cook 

Abstract
 
Periodic motion is one of the most common engineering issues faced.  The goal of these problems is to 
model this periodic motion as a function of time, resulting in a differential equation.  To solve these 
differential equations several methods are commonly employed.  The methods that will be described in 
this paper are all variations of Runge‐Kutta methods, specifically the Euler method, Heun’s method, 
Midpoint method, and the classic fourth‐order Runge‐Kutta method. 
 
Introduction
 
The need to solve periodic motion is seen in many aspects of engineering. Waves and pendulums are 
two examples of periodic motion found in everyday problems. Pendulums specifically have found many 
important uses.  Considered to be one of the most exact forms of time keeping until the invention of the 
quartz clock, pendulums played a vital role in early time management.   
 
Periodic motion is also seen in molecular vibration. Molecular vibration is when a molecule as a whole 
has constant translational and rotational motion. The information gained from knowing theis molecular 
vibration is very important in gaining insight into the Schrodinger wave equation, which lays the 
foundation for modern quantum mechanics [1]. 
 
To model these problems, position and velocity of the object must be known as a function of time.  The 
functions that model this motion are commonly seen as differential equations, meaning that the values 
of the function are based off of the function itself and its derivatives.  Differential equations can become 
very complex, and numerical methods are commonly employed to solve these equations.  Four methods 
will be used in this paper to solve the motion of a pendulum. These methods are the Euler method, 
Heun’s method, the Midpoint method, and finally the Fourth‐order Runge‐Kutta method. 
 
Physical Analysis
 
As stated above, this paper will focus on the harmonic motion of a pendulum system. This system is 
shown in figure 1. 
 
 
Figu
ure 1: Physical Se
et‐up of Pendul um System [2]

 
In this sysstem there is an object of m
mass ‘m’ attaached to a fixeed point ‘P’ b by a string or rrod of length  ‘L’.  
The mass is initially susspended at anngle ‘ϑ’ from which it is reeleased and o oscillates in a harmonic mo otion. 
The forces acting on th he mass, allow
wing it to osciillate, are graavity acting onn the mass an nd the tensilee 
force in thhe string.  Kno
owing this, th
he position off the mass aloong its path o of motion can  be described d in 
term of ϑ and L. 
 
This systeem can be mo odeled using NNewton’s law w of motion, w which takes th he form [2]: 
 
          sin 0 (1) 
 
However, this second o
order differen n has no analyytical solution.  But knowiing that at sm
ntial equation mall 
angles sin
nϑ≈ϑ, we can transform the equation innto a more m anageable lin near differenttial equation [2]: 
 
          0  (2)  
 
From this we can solve
e for the angu
ular displacem
ment at time ‘‘t’ [2]: 
 

          cos (3) 
 
This is a general repressentation of tthe system, but its accuraccy can be called into questtion because this 
solution aassumes that sinϑ≈ϑ which h is only valid at small anguular displacem
ments.  To ob
btain a betterr view 
of the system a numerrical solution is required. B By substitutingg v=dϑ/dt intto equation (1
1) a coupled 
system off two first ord
der equations can be obtained [2]: 
 
 
  (4) 
 
And 
 
sin   (5) 
 
The numerical methods listed above can then be used to solve this coupled system. 
 
Additionally, by substituting equation (3) into equation (4) we obtain a first order differential equation 
that can be used to predict the velocity [2]: 
 

sin cos   (6) 


 
Which can be solved for by integration. 
 
Numerical Analysis
 
All four of the numerical methods mentioned are variations of the Runge‐Kutta methods.  The Runge‐
Kutta methods all rely on the same general idea of finding a new value based on a previous value being 
modified by the slope or derivative, and an increase in the independent variable (a ‘step’). 
 
In equation form this can be represented as: 
 
∗  
 
Or in a more mathematical view [3]: 
 
             (7) 
 
Where φ is the slope or derivative, and ‘h’ is the step size. 
 
Euler’s Method (First‐Order Method) 
 
Euler’s method uses the first derivative of the function at the original ‘x’ value to extrapolate a new ‘y’ 
value.  This means that for this method φ=f(xi, yi)=y’, which is the derivative at the initial ‘x’ value.  The 
general formula for this method is [3]: 
 
,  
 
Graphically this can be
e seen as: 
 

 
Figure 2: Euler's Methodd [4] 

 
The iterattive process o
of extrapolatin ng a new poinnt based off tthe derivativee, then using that new point to 
find anoth her new point continues fo or the duratioon of the funcction interval. 
 
Heun’s MMethod (Secon nd‐Order Metthod) 
 
Heun’s method is know wn as a secon nd‐order method because  it takes the ffunctions deriivative at two o 
points whhen determining a new value.  The derivvative at the  initial value aand the derivaative at the eend 
value are averaged to obtain a slope that is a bettter represenntation of thee actual slope across the 
interval. 
 
This meth hod begins byy finding a pre
edictor, which h is the slope  at the end po
oint.  This preedictor is then

averaged with the slop pe at the initiaal value to ob
btain the corrrector equatioon.  The predictor and 
corrector formulas are e as follows [3
3]: 
 
Predictor::        ,  
, ,
Corrector:       
 
 
be depicted graphically as: 
This can b
 
 
Figure 3: Heun's Methodd [5] 

 
Midpoint Method (Seccond‐Order M Method) 
 
The midpoint method is very similar to Heun’s m method in thaat it uses derivvatives at two
o separate po oints 
ew values.  Th
to find ne he main differrence betwee en the midpoiint method an nd Heun’s meethod is the 
midpoint method take es the derivatiive at the middpoint betweeen the initial and end valuue, while Heuun’s 
method taakes the averrage of the deerivatives at tthe initial andd end values. The formula for this meth
hod is 
[3]: 
 
. , .  
 
 
Graphically the Midpoint method caan be depicte ed as: 
 
 
Figure 4: M
Midpoint Methood [6] 

 
 
Fourth‐Orrder Runge‐K Kutta Methodd 
 
As the name implies, the Fourth‐Orrder Runge‐Ku utta method ttakes derivattives at four d
distinct pointss to 
better app
proximate the slope in thee given intervval.  It then weeights each o
of these derivaative values tto 
gain a mu
uch more accu urate represe
entation of the actual slopee. The formula for this is [3]: 
 
1
2 2
6
 
Where 
 
,
.5 , .5  
.5 , .5  
,  
 
This meth
hod takes the derivatives aat the initial value, two at tthe midpoint,, and one at tthe finial valu
ue. 
Graphically this can be
e seen as: 
 
 
Figu
ure 5: Fourth‐Orrder Runge‐Kuttta Method [7] 

 
Gauss‐Leg
gendre Formu
ulas 

The Gausss‐Legendre Fo ormulas provvide a quick an nd easy way tto solve the integration off functions 
numerically.  It takes thhe weighted sum of functiion values at  specific pointts within the domain of 
on. It should b
integratio be noted thatt the Gauss‐Le egendre Formmulas are onlyy valid within the integratiion 
his a change oof variable is necessary to fit the functiion 
domain of [‐1,1], so if tthe domain iss outside of th
e [‐1,1] domain. This changge of variable
within the e is accomplisshed by usingg the followingg formulas [33]: 
 

 
2
And 
 

 
2
 
Where ‘a’’ is the lower bound of inteegration and ‘b’ is the uppper bound of integration 
 
The generral Gauss‐Leggendre Formu ula is [3]: 
 
≅ ⋯  
 
Where c’ss are the weigghts and x’s are the pointss where the fuunction is to b
be evaluated at. 
 
Two‐Poin
nt Gauss‐Leg
gendre Form
mula 
 
wo point meth
For the tw hod, the weigghts (c’s) are aall 1, and the  function is to
o be evaluateed at ‐1/sqrt(3
3) 
wo point metthod takes this form: 
and 1/sqrrt(3). So the tw
1 1
≅  
√3 √3
The two p
point method has an appro
oximate errorr of: 
≅  
 
Four‐Poin
nt Gauss‐Leg
gendre Form
mula 
 
The four p owing weights and evaluattion points: 
point formulaa has the follo
 
Weights 
W Evaaluation Points 
C0=.3478548 
= X0=‐.861136122 
C1=.6521452 
= X1==‐.3399810444 
C2=.6521452 
= X2=.3399810444 
C3=.3478548 
= X3=.86113612 
Table
e 1: Four‐point G
Gauss‐Legendre  Coefficients [3]] 

Plugging tthese values iinto the gene
eral equation will give the ffourth order solution. 
 
The fourth order gives an approxim mate error of:
≅  
 

Results

we plot theta aas a function of time, and vvelocity as a ffunction of time to give a general estim
Initially w mate 
of the anaalytical solutio
on.  This plot is as follows:: 

 
Figure 6: Analytic Solution of t he System 
 

This confirms that the pendulum is in fact oscillaating back andd fourth with respect to time.  We can now 
look at the results obtaained from th
he various numerical methhods describeed above. 

Each method is evaluated with two step sizes, h=
=.05 and h=.001 

Euler metthod 
 

Euler’s meethod with a step size of h
h=.01 yields th
he following rresults, plotteed on top of tthe analyticall 
solution: 

 
Figure 7: Euler .01 Steep 

And with a step size off h=.05, Euler’’s method yie
elds these ressults, again pllotted on top of the analyttical 
solution: 

 
 
Figure 8: Euler .05 Steep 

Heun’s M
Method 
 

This meth hod, as stated
d above, takess the derivative at two poiints to make tthe extrapolaated slope follow 
the true sslope of the fu
unction more
e closely. Heun’s method w with an intervval of h=.01 yiields the follo
owing 
results: 
 
Figure 9: Heun .01 Steep 

With a ste 05, Heun’s method yields the followingg results: 
ep size of h=.0

 
Figure 10: Heun .05 Steep 
 
 
 
Midpoint Method 
 
With a step size of h=.01, the Midpoint method returns the following results: 
 
Midpoint Angular Displacement Step Size=0.01 Midpoint Angular Velocity Step Size=0.01
0.8 4

0.6 3

0.4 2
Angular Displacement (rad)

Angular Velocity (rad/sec


0.2 1

0 0

-0.2 -1

-0.4 -2

-0.6 -3

-0.8 -4
0 0.5 1 1.5 2 0 0.5 1 1.5 2
Time (s) Time (s)
 
Figure 11: Midpoint .01 Step 

 
And with a step of h=.05, the Midpoint results are: 
 
Midpoint Angular Displacement Step Size=0.05 Midpoint Angular Velocity Step Size=0.05
0.8 4

0.6 3

0.4 2
Angular Displacement (rad)

Angular Velocity (rad/sec


0.2 1

0 0

-0.2 -1

-0.4 -2

-0.6 -3

-0.8 -4
0 0.5 1 1.5 2 0 0.5 1 1.5 2
Time (s) Time (s)
 
Figure 12: Midpoint .05 Step 

Fourth Order Range‐Kutta 
 
For a step size of h=.01, the fourth‐order Range‐Kutta method returns the following results: 
 
4th Order RK Solution Angular Displacment Step Size=0.01 4th Order RK Angular Velocity Step Size=0.01
1 4

0.8
3

0.6
2
0.4
Angular Displacement (rad)

Angular Velocity (rad/sec

1
0.2

0 0

-0.2
-1

-0.4
-2
-0.6

-3
-0.8

-1 -4
0 0.5 1 1.5 2 0 0.5 1 1.5 2
Time (s) Time (s)

 
Figure 13: RK .01 Step 
And with a step of h=.05 
4th Order RK Solution Angular Displacment Step Size=0.05 4th Order RK Angular Velocity Step Size=0.05
1 4

0.8
3

0.6
2
0.4
Angular Displacement (rad)

Angular Velocity (rad/sec


1
0.2

0 0

-0.2
-1

-0.4
-2
-0.6

-3
-0.8

-1 -4
0 0.5 1 1.5 2 0 0.5 1 1.5 2
Time (s) Time (s)

 
Figure 14: RK .05 Step 

 
Finally we can examine the values of each of the methods at t=2, and compare these values with the 
integration values of equation (6) using the two and four point Gauss‐Legendre Methods: 
 
Method Step Size Velocity at t=2
Analytical  N/A  ‐3.1054 
Euler  0.01  ‐3.470153 
   0.05  ‐4.454886 
Heun  0.01  ‐3.040576 
   0.05  ‐3.074375 
Midpoint  0.01  ‐3.040706 
   0.05  ‐3.076673 
4th Order RK  0.01  ‐3.181253 
   0.05  ‐3.726941 
Two Point Gauss  N/A  ‐9.800047 
Four Point Gauss  N/A  ‐3.285373 
Table 2: Comparison of Results at t=2 


Discussiion
 
Upon examining these results it beccomes immed diately appareent that higher order (and d therefore 
derivativees taken at more points) an nd a smaller sstep size resuults in more accurate resullts.  When usiing 
numerical methods to solve differential equation ns there are ttwo types of eerrors, truncaation and rou
und‐
off.  Rounnd‐off errors aare due to thee limitations o
of the compuuter when deaaling with significant digitss and 
this type oof error cannot be easily cchanged.  Truncation errorrs are caused by the nature of the 
technique es used to find values of y. 
 
Looking at the general equation forr the numerical methods uused (equation (7)), it can b be seen that more 
accurate aapproximatio ons of the slop pe result in m
more accuratee y values.  Ass more positioons are used 
(higher orrder), the estiimate for the slope becom mes more accuurate with respect to the eexact solution n, 
and there efore the y values become more accurate.  So impro ving the accu uracy of each y value decreeases 
the local ttruncation error.   
 
Runge‐Kutta methods use previous values to esttimate new vaalues, so inacccuracies in old y values caause 
errors to pile up.  Each
h time an iteraation of the nnumerical metthod occurs tthis error getss larger and 
ooking at the results sectio
larger.  Lo on, this explains why the e stimates are almost exactt in the beginn ning 
of the currve, but tend to stray awayy from the exact solution nnear the end..  This type off error is knowwn as 
propagate ed error.   
 
By increassing the order and thus the accuracy off the slope, annd reducing tthe step size b both local andd 
propagate ed error can b be reduced.  CConsider the following graaph: 
 
 

 
Figure
e 15: Effects of O
Order and Step  Size on Error [8] 
 
Take the Euler method in the above graph as an example.  Because the next y value will be based upon 
that line, the closer that line is to the next true point, the better the new y value will be.  It can also be 
seen that as the step grows larger, the slope becomes farther from the exact solution, so cutting step 
size can greatly improve accuracy.  By reducing the step size by half, the global error for Euler’s method 
is also halved. 
 
It is worth noting the local and global truncation error for each of the numerical methods: 
 
Method Local Error Global Error
2
Euler  O(h )  O(h) 
Heun  O(h3)  O(h2) 
Midpoint  O(h3)  O(h2) 
4th Order RK  O(h5)  O(h4) 
Table 3: Comparison of Error [3] 

What this table essentially shows is that a decrease in step size will cause the Heun/Midpoint/fourth 
order methods to decrease in error at a faster rate than Euler’s method 
 
Conclusion
 
As can be seen from the above results, there are many methods that can be used to solve a coupled 
system of equations.  All of these methods have their trade‐offs when compared to each other.  Euler’s 
method is relatively inaccurate, but it is not intensive on computer resources and it is easier to program.  
The fourth‐order Runge‐Kutta is the most accurate of the methods examined, but it can be taxing on 
system resources and is more labor intensive to program.  This is why one method cannot be favored 
over another, and it is important to assess what is needed from the output; accuracy or low time/money 
investment. 
 
References
 
[1] "Molecular vibration ‐ Wikipedia, the free encyclopedia." Wikipedia, the free encyclopedia. N.p., n.d. 
Web. 15 Nov. 2010. <http://en.wikipedia.org/wiki/Molecular_vibration>.  
 
[2] Drapaca, Corina. Project 3: Numerical Analysis of the Swinging Simple Pendulum. Pennsylvania State 
University, 2010. Print. 
 
[3] Chapra, Steven C., and Raymond P. Canale. Numerical methods for engineers . 6th ed. Boston: 
Mcgraw‐Hill Higher Education, 2010. Print.  
 
[4] "Euler's Method for First Order Differential Equations." Swarthmore. N.p., n.d. Web. 15 Nov. 2010. 
<http://www.swarthmore.edu/NatSci/echeeve1/Ref/NumericInt/Euler1.html>. 
 
[5] "Numerical Tutorials : Euler's Method." Computer Engineering, Chulalongkorn University . N.p., n.d. 
Web. 15 Nov. 2010. <http://www.cp.eng.chula.ac.th/~u43ptg/euler.html>.  
 
[6] "Midpoint Method." Wikipedia, the free encyclopedia. N.p., n.d. Web. 15 Nov. 2010. 
<http://en.wikipedia.org/wiki/Midpoint_method>.  
 
[7] "ODE‐2: Runge‐Kutta." Boston College Physics. N.p., n.d. Web. 15 Nov. 2010. 
<http://physics.bc.edu/MSC/430/T2/ODE2.html>.  
 
[8] "Runge ‐ Kutta." Drexel University: Department of Physics: Home. N.p., n.d. Web. 15 Nov. 2010. 
<http://einstein.drexel.edu/courses/Comp_Phys/Integrators/rk4.html>.   
 
Appendix 
 
Variables 
ti=0;
tf=2;
theta(1)=pi/4;
v(1)=0;
g=32.2;
L=2;
 
Euler’s  
 
%Set the step size and number of calculations
h=.01;
nc=(tf-ti)/h+1;

%Euler's algorithm
for i=2:nc
theta(i) = theta(i-1) +v(i-1)*h;
v(i) = v(i-1) + - g/L *sin(theta(i-1))*h;
end

fprintf('\nThe velocity at t=2 by the Euler Method with step-size 0.01 is %f


\n\n', v(i))

%graphing results
t=0:0.01:2;

figure
hold on, subplot(1,2,2), plot(t,v,'r');
title('Eulers Angular Velocity Step Size=0.01')
xlabel('Time (s)')
ylabel('Angular Velocity (rad/sec')
grid on
hold on, subplot(1,2,1), plot(t,theta,'r');
title('Eulers Angular Displacement Step Size=0.01')
xlabel('Time (s)')
ylabel('Angular Displacement (rad)')
grid on

for i = 1:201
position(i) = pi/4*cos(sqrt(g/L)*t(i));
velocity(i) = -sqrt(g/L)*(pi/4)*sin(sqrt(g/L)*t(i));
end
hold on, subplot(1,2,1), plot(t,position,'b');
hold on, subplot(1,2,2), plot(t,velocity,'b');

%Euler's Method (h=0.05)


clear all

%For Equations (5)n and (6)


%Initialize variables
ti=0;
tf=2;
theta(1)=pi/4;
v(1)=0;
g=32.2;
L=2;

%Set the step size and number of calculations


h=.05;
nc=(tf-ti)/h+1;

%Euler's algorithm
for i=2:nc
theta(i) = theta(i-1) +v(i-1)*h;
v(i) = v(i-1) + - g/L *sin(theta(i-1))*h;
end

fprintf('\nThe velocity at t=2 by the Euler Method with step-size 0.05 is %f


\n\n', v(i))

%graphing results
t=0:0.05:2;

figure
hold on, subplot(1,2,2), plot(t,v,'r');
title('Eulers Angular Velocity Step Size=0.05')
xlabel('Time (s)')
ylabel('Angular Velocity (rad/sec')
grid on
hold on, subplot(1,2,1), plot(t,theta,'r');
title('Eulers Angular Displacement Step Size=.05')
xlabel('Time (s)')
ylabel('Angular Displacement (rad)')
grid on

for i = 1:41
position(i) = pi/4*cos(sqrt(g/L)*t(i));
velocity(i) = -sqrt(g/L)*(pi/4)*sin(sqrt(g/L)*t(i));
end
hold on, subplot(1,2,1), plot(t,position,'b');
hold on, subplot(1,2,2), plot(t,velocity,'b');

Heun’s 
%Initialize variables
ti=0;
tf=2;
theta(1)=pi/4;
v(1)=0;
g=32.2;
L=2;

%Set the step size and number of calculations


h=.01;
nc=(tf-ti)/h+1;

%Heun's algorithm
for i=2:nc
thetap(i) = theta(i-1) +v(i-1)*h;
vp(i) = v(i-1) + - g/L *sin(theta(i-1))*h;
theta(i) = theta(i-1) + (vp(i)+v(i-1))/2*h;
v(i) = v(i-1) + (-g/L*sin(theta(i-1))+(-g/L*sin(thetap(i))))/2*h;
end

fprintf('\nThe velocity at t=2 by the Heun Method with step-size 0.01 is %f


\n\n', v(i))

%graphing results
t=0:0.01:2;

figure
hold on, subplot(1,2,2), plot(t,v,'r');
title('Heuns Angular Velocity Step Size =0.01)')
xlabel('Time (s)')
ylabel('Angular Velocity (rad/sec')
grid on
hold on, subplot(1,2,1), plot(t,theta,'r');
title('Heuns Angular Displacment Step Size=0.01')
xlabel('Time (s)')
ylabel('Angular Displacement (rad)')
grid on

for i = 1:201
position(i) = pi/4*cos(sqrt(g/L)*t(i));
velocity(i) = -sqrt(g/L)*(pi/4)*sin(sqrt(g/L)*t(i));
end

hold on, subplot(1,2,1), plot(t,position,'b');


hold on, subplot(1,2,2), plot(t,velocity,'b');
%Heun's Method (h=0.05)
clear all

%For Equations (5) and (6)


%Initialize variables
ti=0;
tf=2;
theta(1)=pi/4;
v(1)=0;
g=32.2;
L=2;

%Set the step size and number of calculations


h=.05;
nc=(tf-ti)/h+1;

%Heun's algorithm
for i=2:nc
thetap(i) = theta(i-1) +v(i-1)*h;
vp(i) = v(i-1) + - g/L *sin(theta(i-1))*h;
theta(i) = theta(i-1) + (vp(i)+v(i-1))/2*h;
v(i) = v(i-1) + (-g/L*sin(theta(i-1))+(-g/L*sin(thetap(i))))/2*h;
end

fprintf('\nThe velocity at t=2 by the Heun Method with step-size 0.05 is %f


\n\n', v(i))

%graphing results
t=0:0.05:2;

figure
hold on, subplot(1,2,2), plot(t,v,'r');
title('Heuns Angular Velocity Step Size=0.05)')
xlabel('Time (s)')
ylabel('Angular Velocity (rad/sec')
grid on
hold on, subplot(1,2,1), plot(t,theta,'r');
title('Heuns Angular Displacment Step Size=0.05)')
xlabel('Time (s)')
ylabel('Angular Displacement (rad)')
grid on

for i = 1:41
position(i) = pi/4*cos(sqrt(g/L)*t(i));
velocity(i) = -sqrt(g/L)*(pi/4)*sin(sqrt(g/L)*t(i));
end

hold on, subplot(1,2,1), plot(t,position,'b');


hold on, subplot(1,2,2), plot(t,velocity,'b');
 

 
Midpoint 
ti=0;
tf=2;
theta(1)=pi/4;
v(1)=0;
g=32.2;
L=2;

%Set the step size and number of calculations


h=.01;
nc=(tf-ti)/h+1;

%Midpoint algorithm
for i=2:nc
thetap(i) = theta(i-1) +v(i-1)*h/2;
vp(i) = v(i-1) + - g/L *sin(theta(i-1))*h/2;
theta(i) = theta(i-1) + vp(i)*h;
v(i) = v(i-1) + (-g/L*sin(thetap(i)))*h;
end

fprintf('\nThe velocity at t=2 by the Midpoint Method with step-size 0.01 is


%f \n\n', v(i))

%graphing results
t=0:0.01:2;

figure
hold on, subplot(1,2,2), plot(t,v,'r');
title('Midpoint Angular Velocity Step Size=0.01')
xlabel('Time (s)')
ylabel('Angular Velocity (rad/sec')
grid on
hold on, subplot(1,2,1), plot(t,theta,'r');
title('Midpoint Angular Displacement Step Size=0.01')
xlabel('Time (s)')
ylabel('Angular Displacement (rad)')
grid on

for i = 1:201
position(i) = pi/4*cos(sqrt(g/L)*t(i));
velocity(i) = -sqrt(g/L)*(pi/4)*sin(sqrt(g/L)*t(i));
end

hold on, subplot(1,2,1), plot(t,position,'b');


hold on, subplot(1,2,2), plot(t,velocity,'b');

%Midpoint Method (h=0.05)


clear all
%For Equations (5) and (6)
%Initialize variables
ti=0;
tf=2;
theta(1)=pi/4;
v(1)=0;
g=32.2;
L=2;

%Set the step size and number of calculations


h=.05;
nc=(tf-ti)/h+1;

%Midpoint algorithm
for i=2:nc
thetap(i) = theta(i-1) +v(i-1)*h/2;
vp(i) = v(i-1) + - g/L *sin(theta(i-1))*h/2;
theta(i) = theta(i-1) + vp(i)*h;
v(i) = v(i-1) + (-g/L*sin(thetap(i)))*h;
end

fprintf('\nThe velocity at t=2 by the Midpoint Method with step-size 0.05 is


%f \n\n', v(i))

%graphing results
t=0:0.05:2;

figure
hold on, subplot(1,2,2), plot(t,v,'r');
title('Midpoint Angular Velocity Step Size=0.05')
xlabel('Time (s)')
ylabel('Angular Velocity (rad/sec')
grid on
hold on, subplot(1,2,1), plot(t,theta,'r');
title('Midpoint Angular Displacement Step Size=0.05')
xlabel('Time (s)')
ylabel('Angular Displacement (rad)')
grid on

for i = 1:41
position(i) = pi/4*cos(sqrt(g/L)*t(i));
velocity(i) = -sqrt(g/L)*(pi/4)*sin(sqrt(g/L)*t(i));
end

hold on, subplot(1,2,1), plot(t,position,'b');


hold on, subplot(1,2,2), plot(t,velocity,'b');

 
 
Fourth‐Order RK 
 
ti=0;
tf=2;
theta(1)=pi/4;
v(1)=0;
g=32.2;
L=2;

%Set the step size and number of calculations


h=.01;
nc=(tf-ti)/h+1;

%4th Order RK algorithm


for i=2:nc

vp(i-1)=v(i-1)+2*(-g/L*sin(theta(i-1))*h/2);
thetap(i-1)=theta(i-1)+vp(i-1)*h/2;
vpp(i-1)=v(i-1)+(-g/L*sin(thetap(i-1))*h/2);
thetapp(i-1)=theta(i-1)+vpp(i-1)*h;
vppp(i-1)=v(i-1)+(-g/L*sin(thetapp(i-1))*h);
theta(i)=theta(i-1)+1/6*h*(v(i-1)+2*vp(i-1)+2*vpp(i-1)+vppp(i-1));
v(i)=v(i-1)+(-g/L*sin(theta(i-1))*h);

end

fprintf('\nThe velocity at t=2 by the 4th order Runge-Kutta Method with step-
size 0.01 is %f \n\n', v(i))

%graphing results
t=0:0.01:2;

figure
hold on, subplot(1,2,2), plot(t,v,'r');
title('4th Order RK Angular Velocity Step Size=0.01')
xlabel('Time (s)')
ylabel('Angular Velocity (rad/sec')
grid on
hold on, subplot(1,2,1), plot(t,theta,'r');
title('4th Order RK Solution Angular Displacment Step Size=0.01')
xlabel('Time (s)')
ylabel('Angular Displacement (rad)')
grid on

for i = 1:201
position(i) = pi/4*cos(sqrt(g/L)*t(i));
velocity(i) = -sqrt(g/L)*(pi/4)*sin(sqrt(g/L)*t(i));
end

hold on, subplot(1,2,1), plot(t,position,'b');


hold on, subplot(1,2,2), plot(t,velocity,'b');
%4th order RK Method (h=0.05)
clear all

%For Equations (5) and (6)


%Initialize variables
ti=0;
tf=2;
theta(1)=pi/4;
v(1)=0;
g=32.2;
L=2;

%Set the step size and number of calculations


h=.05;
nc=(tf-ti)/h+1;

%4th Order RK algorithm


for i=2:nc

vp(i-1)=v(i-1)+2*(-g/L*sin(theta(i-1))*h/2);
thetap(i-1)=theta(i-1)+vp(i-1)*h/2;
vpp(i-1)=v(i-1)+(-g/L*sin(thetap(i-1))*h/2);
thetapp(i-1)=theta(i-1)+vpp(i-1)*h;
vppp(i-1)=v(i-1)+(-g/L*sin(thetapp(i-1))*h);
theta(i)=theta(i-1)+1/6*h*(v(i-1)+2*vp(i-1)+2*vpp(i-1)+vppp(i-1));
v(i)=v(i-1)+(-g/L*sin(theta(i-1))*h);

end

fprintf('\nThe velocity at t=2 by the 4th order Runge-Kutta Method with step-
size 0.05 is %f \n\n', v(i))

%graphing results
t=0:0.05:2;

figure
hold on, subplot(1,2,2), plot(t,v,'r');
title('4th Order RK Angular Velocity Step Size=0.05')
xlabel('Time (s)')
ylabel('Angular Velocity (rad/sec')
grid on
hold on, subplot(1,2,1), plot(t,theta,'r');
title('4th Order RK Solution Angular Displacment Step Size=0.05')
xlabel('Time (s)')
ylabel('Angular Displacement (rad)')
grid on

for i = 1:41
position(i) = pi/4*cos(sqrt(g/L)*t(i));
velocity(i) = -sqrt(g/L)*(pi/4)*sin(sqrt(g/L)*t(i));
end

hold on, subplot(1,2,1), plot(t,position,'b');


hold on, subplot(1,2,2), plot(t,velocity,'b');
 

You might also like