% Igor Yanovsky
% Teaching Assistant
% Math 151B
% 03/06/07
%
% Section 5.2, problem 11(a)
%
%#####################################################################
%
% This program solves the ordinary differential equation
%
% dy/dt = -y + t + 1, 0 <= t <= 5
% y(0) = 1
%
% using Euler's method. The function defining the ODE is defined in a
% separate Matlab function.
%
% This program also finds the error of the approximation by comparing the
% approximate solution and the exact solution y(t) = exp(-t)+t.
%
%#####################################################################

clear all

format long

% ODE Specification
%

t0 = 0.0;
tF = 5.0;
y0 = 1.0;

h = 0.2 % timestep
N = (tF-t0)/h % number of timesteps

tn = t0;
wn = y0;

for(i=1:N)
wnp1 = wn + h*f(tn,wn); % advances the ODE one step using Euler's method
wn = wnp1;
tn = tn + h;
end

wn;
tn;

yexact = exp(-tn) + tn;
error = abs(wn - yexact);

fprintf(1,'N = %3d',N); fprintf(1,', h = %4.2f',h); fprintf(1,',\n');
fprintf(1,'w = %5.8f', wn ); fprintf(1,',\n');
fprintf(1,'y = %5.8f', yexact); fprintf(1,',\n');
fprintf(1,'E = %5.8f', error ); fprintf(1, '\n');

clear all