In: Advanced Math
y' = 2 + t^2 + y^2 0<t<1 y(0)=0
use the euler method to determine step size (h) to keep global
truncation error below .0001
clear all
close all
%function for which Euler method have to calculate
f=@(y,t) 2+t.^2+y.^2;
err=1;
N=10; count=0;
c1(1)=inf;
tol=0.0001;
while err>tol
count=count+1;
[y1_result,t_result] =
euler_method(f,0,0,1,N);
err=abs(c1(count)-y1_result(end));
c1(count+1)=y1_result(end);
N=N+1;
end
plot(t_result,y1_result)
xlabel('time')
ylabel('y(t)')
title('y(t) vs. t plot')
box on
fprintf('Step size required for error less than 0.0001 is
%f\n',(1/N))
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%Matlab code for Euler's forward
function [y1_result,t_result] = euler_method(f,y0,t0,tend,N)
%function for Euler equation solution
%all step size
h=(tend-t0)/N;
%Initial values
%t end values
tn=t0:h:tend;
% Euler steps
y1_result(1)=y0;
t_result(1)=t0;
for i=1:length(tn)-1
t_result(i+1)=
t_result(i)+h;
y1_result(i+1)=y1_result(i)+h*double(f(y1_result(i),t_result(i)));
end
end
%%%%%%%%%%%%%%%%%%% End of Code %%%%%%%%%%%%%%%%%