ESSE 2030 Lab 1: Runge-Kutta Method (RK4) Deliverables: Deliverable 1
ESSE 2030 Lab 1: Runge-Kutta Method (RK4) Deliverables: Deliverable 1
These were the approximated values for the solution at t=20. The RK4 approximation is orders of magnitude
closer to the exact solution compared to the Euler method approximation.
Deliverable 2
Please note that the suggested method of plotting the results with a log scale on the y-axis using semilog(x,y)
is buggy when used in conjunction with hold on which is necessary to plot all three lines on the same figure. I
manually set the y-axis scale to logarithmic using the set function.
Deliverable 3
%ESSE 2030 Lab1
%Author: Arinze Anozie
clear all;
h = 0.5; %Step size
t0 = 0; %Initial time
tf = 100; %Final time t
t = 0:h:tf; %Times
y0 = exp(1); %Initial value
f = @(t, y) (t*y); %y'
%Initial values and memory allocation
rk4 = zeros(1, numel(t));
rk4(1) = y0;
euler = zeros(1, numel(t));
euler(1) = y0;
y = zeros(1, numel(t));
%Compute RK4 and Euler approximations
for i=1:numel(t)-1
k1 = f(t(i), rk4(i));
k2 = f(t(i)+h/2, rk4(i) + h*k1/2);
k3 = f(t(i)+h/2, rk4(i) + h*k2/2);
k4 = f(t(i)+h, rk4(i) + h*k3);
rk4(i+1) = rk4(i) + (h/6)*(k1 + 2*k2 + 2*k3 + k4);
euler(i+1) = euler(i) + h * f(t(i), euler(i));
y(i) = exp((t(i)^2)/2 + 1);
end
%Getting value of approximations at t=20
t20 = find(t == 20);
fprintf('RK4: %e\n', rk4(t20));
fprintf('Euler: %e\n', euler(t20));
fprintf('Exact: %e\n', y(t20));
%Plotting results
figure;
hold on;
title("Numerical Approximation of Soln to y'=ty");
plot(t, rk4);
plot(t, euler);
plot(t, y);
set(gca, 'yscale', 'log');
xlabel('t'); ylabel('log y');
legend('RK4', 'Euler', 'Exact Soln');
hold off;