%A script that illustrates Euler's method
lamda=-1;

%define time span
t0=0; tend=1;

%set initial condition
y0=1;

%timestep
dt=0.25; 

%the number of timesteps (no adaptive timesteps yet)
nt=round((tend-t0)/dt+realmin);

%initialize
clear y t;
y(1)=y0;
t(1)=t0;

%Euler's method
for i=1:nt;
    t(i+1)=t(i)+dt;
    y(i+1)=y(i)+dt*lamda*y(i);    
end

%exact solution
nt_exact=10000;
t_exact=(1:nt_exact+1)*(tend-t0)/nt_exact+t0;
y_exact=y0*exp(lamda*t_exact);

%plotting the results
figure(10)
set(0,'DefaultAxesfontsize',20);
set(0,'Defaultlinelinewidth',1.2);
hold off
plot(t,y);xlabel('time');ylabel('y');axis([t0 tend -inf inf]);
hold on;
plot(t_exact,y_exact,'r');
plot(t,y,'o');
legend('Euler','Exact solution' );
dtratio=dt*nt_exact/(tend-t0);
for i=2:nt
    irange=((i-1)*dtratio+1:i*dtratio);
    plot(t_exact(irange),y_exact(irange)*y(i)/y0/exp(lamda*t(i)),'r--');
end
