In: Advanced Math
y′ = t, y(0) = 1, solution: y(t) = 1+t2/2
y′ = 2(t + 1)y, y(0) = 1, solution: y(t) = et2+2t
y′ = 5t4y, y(0) = 1, solution: y(t) = et5
y′ = t3/y2, y(0) = 1, solution: y(t) = (3t4/4 + 1)1/3
For the IVPs above, make a log-log plot of the error of Explicit Trapezoidal Rule at t = 1 as a function ofhwithh=0.1×2−k for0≤k≤5.
MATLAB Code:
close all
clear
clc
k = 0:1:5;
H = 0.1 * 2.^(-k);
f = @(t,y) t; % Given ODE
y_exact = @(t) 1 + t^2 / 2;
y(1) = 1; % Initial condition
ti = 0; tf = 1; % Interval of t
yf_vec = []; % Vector for storing y(t = 1) for different step
sizes
for i = 1:length(H)
h = H(i);
t = ti:h:tf;
for j = 1:length(t)-1
y(j+1) = y(j) + 0.5*h*(f(t(j), y(j)) + f(t(j) + h, y(j) + h*f(t(j),
y(j)))); % Explicit Trapz. Method
end
yf_vec = [yf_vec, y(end)]; % Store the value of y(t = 1)
end
figure, loglog(H, abs(y_exact(1) - yf_vec), 'o-'), xlabel('h'),
ylabel('Error')
title(sprintf('Log-Log plot of Error of Explicit Trapz. Method at t
= 1\nODE: y'' = t'))
f = @(t,y) 2*(t + 1)*y; % Given ODE
y_exact = @(t) exp(t^2 + 2*t);
y(1) = 1; % Initial condition
ti = 0; tf = 1; % Interval of t
yf_vec = []; % Vector for storing y(t = 1) for different step
sizes
for i = 1:length(H)
h = H(i);
t = ti:h:tf;
for j = 1:length(t)-1
y(j+1) = y(j) + 0.5*h*(f(t(j), y(j)) + f(t(j) + h, y(j) + h*f(t(j),
y(j)))); % Explicit Trapz. Method
end
yf_vec = [yf_vec, y(end)]; % Store the value of y(t = 1)
end
figure, loglog(H, abs(y_exact(1) - yf_vec), 'o-'), xlabel('h'),
ylabel('Error')
title(sprintf('Log-Log plot of Error of Explicit Trapz. Method at t
= 1\nODE: y'' = 2(t + 1)y'))
f = @(t,y) 5 * t^4 * y; % Given ODE
y_exact = @(t) exp(t^5);
y(1) = 1; % Initial condition
ti = 0; tf = 1; % Interval of t
yf_vec = []; % Vector for storing y(t = 1) for different step
sizes
for i = 1:length(H)
h = H(i);
t = ti:h:tf;
for j = 1:length(t)-1
y(j+1) = y(j) + 0.5*h*(f(t(j), y(j)) + f(t(j) + h, y(j) + h*f(t(j),
y(j)))); % Explicit Trapz. Method
end
yf_vec = [yf_vec, y(end)]; % Store the value of y(t = 1)
end
figure, loglog(H, abs(y_exact(1) - yf_vec), 'o-'), xlabel('h'),
ylabel('Error')
title(sprintf('Log-Log plot of Error of Explicit Trapz. Method at t
= 1\nODE: y'' = 5t^4y'))
f = @(t,y) t^3 / y^2; % Given ODE
y_exact = @(t) (3 * t^4 / 4 + 1)^(1/3);
y(1) = 1; % Initial condition
ti = 0; tf = 1; % Interval of t
yf_vec = []; % Vector for storing y(t = 1) for different step
sizes
for i = 1:length(H)
h = H(i);
t = ti:h:tf;
for j = 1:length(t)-1
y(j+1) = y(j) + 0.5*h*(f(t(j), y(j)) + f(t(j) + h, y(j) + h*f(t(j),
y(j)))); % Explicit Trapz. Method
end
yf_vec = [yf_vec, y(end)]; % Store the value of y(t = 1)
end
figure, loglog(H, abs(y_exact(1) - yf_vec), 'o-'), xlabel('h'),
ylabel('Error')
title(sprintf('Log-Log plot of Error of Explicit Trapz. Method at t
= 1\nODE: y'' = t^3/y^2'))
Plots: