%% Specifying tolerances for ode45
%% Example problem

clearvars; clf

% Consider the initial value problem
%       y'=2y-\sin t-2\cos t,\qquad y(0)=1
% Here the exact solution is y(t)=\cos t. We can easily verify this by plugging this into the ODE.
% We plot the direction field and the exact solution together:

f = @(t,y) 2*y-sin(t)-2*cos(t);
dirfield(f,0:.25:6,-1.5:.25:1.5); hold on
T = 6;
fplot(@(t)cos(t),[0 T],'k')        % plot cos(t) as black curve
title('exact solution of IVP')

%
%% Solve with ode45 using default tolerances
% We use ode45 to solve this IVP for t\in [0,T]

[ts,ys] = ode45(f,[0,T],1);
plot(ts,ys,'b')
title('solution obtained by ode45 (blue)')

% At t=8 we should get for y(t) the value

cos(T)

% But the solution from ode45 gives

ys(end)

%
%% Solve with ode45 using smaller tolerances
% We now choose smaller values for RelTol (default 1e-3) and AbsTol (default 1e-6):

opt = odeset('RelTol',1e-5,'AbsTol',1e-8);     % try using even smaller values
[ts,ys] = ode45(f,[0,T],1,opt);      % solve with options given by opt
plot(ts,ys,'g')
title('solution obtained by ode45 with smaller tolerances (green)')
hold off

% At t=T we should get for y(t) the value

cos(T)

% Now the solution from ode45 gives

ys(end)

% Try to use even smaller values for the tolerances!