% Igor Yanovsky
% Teaching Assistant
% Math 151B
% 03/06/07
%
% Section 5.2, problem 12
%
%#####################################################################
%
% This program solves the ordinary differential equation
% 
%  dy/dt = -y+1,    0 <= t <= 1
%  y(0) = 0
% 
% 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) = 1 - exp(-t).
% 
%#####################################################################

clear all

format long

% ODE Specification
%

t0 = 0.0;
tF = 1.0;
y0 = 0.0;

h = 0.1             % timestep
N = (tF-t0)/h       % number of timesteps

tn = t0;
wn = y0;

for(i=1:N)
    wnp1 = wn + h*f(wn,tn); % advances the ODE one step using Euler's method
    wn = wnp1;
    tn = tn + h;
end

wn;
tn;

yexact = 1 - exp(-tn);
error = abs(wn - yexact);

fprintf(1,'N = %3d',N);  fprintf(1,', h = %4.2f',h);  fprintf(1,', t = %4.2f',tn);  fprintf(1,',\n');
fprintf(1,'w = %5.10e', wn    );  fprintf(1,',\n');
fprintf(1,'y = %5.10e', yexact);  fprintf(1,',\n');
fprintf(1,'error = %5.10e', error );  fprintf(1, '\n');
   
clear all
