%% Improved Euler method %% 

%% Written for x'=f(x) with f(x)=-x and x(0)=x0


dt=.1;

x0=1;

t0=0;


endtime=1;

t=0:dt:endtime;


N=(endtime-t0)/dt;


x(1)=x0;



for n=1:N


    trial_x=x(n)-dt*x(n);

    x(n+1)=x(n)+0.5*(-x(n)-trial_x)*dt;

    

end


plot(t,x,'k')

hold on



%% END IMPROVED EULER METHOD %%



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% For our simple example we can find the real solution:

A=x0; %Define the constant

x_realsoln_final=A*exp(-endtime); %The solution at the last step to calculate error

x_real=A.*exp(-1.*t); %The general Solution


plot(t,x_real,'b')

hold off


Error=abs(x_realsoln_final-x(N+1)) %In this case the error the difference between the real and numerical solutions.

% In general you would skip the step above because you do not know the real solution!

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%