Specifying tolerances for ode45

Example problem

clearvars; clf
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
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
[ts,ys] = ode45(f,[0,T],1);
plot(ts,ys,'b')
title('solution obtained by ode45 (blue)')
At we should get for the value
cos(T)
ans = 0.96017
But the solution from ode45 gives
ys(end)
ans = -3.6604

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 we should get for the value
cos(T)
ans = 0.96017
Now the solution from ode45 gives
ys(end)
ans = 0.78927
Try to use even smaller values for the tolerances!