Department of Chemical Engineering
Department of Chemical Engineering
Assignment No. 02
Submitted to
for
Runge-Kutta Method
where,
y is an unknown function of time t, which may be scalar or vector quantity
y' is the rate of change of y with respect to t
t0 is the initial value of t
y0 is the value of y at time t0
Let ‘h’ be the step size such that h > 0. Now, the generation term of the series can be defined as:
Page 2 of 8
Solving an example of Runge-Kutta method in MATLAB:
Let’s analyze and solve an initial value problem using Runge-Kutta method. We have to
approximate y(1.5) using RK2 method in this problem:
In the following, is given the MATALB code for solving this problem:
function a = RungeKutta(df)
% asking initial conditions
df=@(t,y)1-t*y
switch r
case 1
% calculating the value of h
n =ceil( (x1-x0)/sqrt(tol));
h = ( x1 - x0)/n;
for i = 1 : n
X(1,1) = x0; Y (1,1) = y0;
k1 = h*feval( df , X(1,i), Y(1,i));
k2 = h*feval( df , X(1,i) + h , Y(1,i) + k1);
k = 1/2* ( k1+ k2);
X( 1, i+1) = X(1,i) + h;
Y( 1 ,i+1) = Y(1,i) + k;
end
case 2
% calculating the value of h
n =ceil( (x1-x0)/nthroot(tol,3));
h = ( x1 - x0)/n;
for i = 1 : n
X(1,1) = x0; Y (1,1) = y0;
k1 = h*feval( df , X(1,i), Y(1,i));
k2 = h*feval( df , X(1,i) + h/2, Y(1,i) + k1);
k3 = h*feval( df , X(1,i) + h, Y(1,i) + k2);
k = 1/6* ( k1+ 4*k2 + k3);
X( 1, i+1) = X(1,i) + h;
Y( 1 ,i+1) = Y(1,i) + k;
end
case 3
Page 3 of 8
% calculating the value of h
n =ceil( (x1-x0)/nthroot(tol,3));
h = ( x1 - x0)/n;
for i = 1 : n
X(1,1) = x0; Y (1,1) = y0;
k1 = h*feval( df , X(1,i), Y(1,i));
k2 = h*feval( df , X(1,i) + h/2, Y(1,i) + k1);
k3 = h*feval( df , X(1,i) + h/2, Y(1,i) + k2);
k4 = h*feval( df , X(1,i) + h, Y(1,i) + k3);
k = 1/6* ( k1+ 2*k2 + 2*k3 + k4);
X( 1, i+1) = X(1,i) + h;
Y( 1 ,i+1) = Y(1,i) + k;
end
end
%displaying results
%displaying graph
x = 1:n+1;
y = Y(1,n+1)*ones(1,n+1) - Y(1,:);
plot(x,y,'r')
xlabel = (' no of interval ');
ylabel = ( ' Error ');
Following are the screenshots of the code written and executed in MATLAB along with graph:
Page 4 of 8
Figure 1
Figure 2
Page 5 of 8
Figure 3
Figure 4
Page 6 of 8
Output:
Figure 5
Figure 6
Page 7 of 8
Graph:
Figure 7
Page 8 of 8