Specifying tolerances for ode45
Example problem
Consider the initial value problem
Here the exact solution is
. 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
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 
[ts,ys] = ode45(f,[0,T],1);
title('solution obtained by ode45 (blue)')
At
we should get for
the value But the solution from ode45 gives
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
title('solution obtained by ode45 with smaller tolerances (green)')
At
we should get for
the value Now the solution from ode45 gives
Try to use even smaller values for the tolerances!