% the program takes the initial data y_0 at the initial time x_0 and 
% computes up to time x_final using N timesteps of size dx.  It creates
% two vectors, x and y, which you can then plot against each other
% plot(x,y)
%
% To call the routine, use the command:
%
% [x,y] = adams_bashforth_3(y_0,x_0,x_final,N,@f)
%
function [x,y] = adams_bashforth_3(y_0,x_0,x_final,N,f)

% step-size:
dx = (x_final-x_0)/N;

% for dy/dx = f(x,y(x))
%
% y(x+dx) ~ y(x)+dx/12*(23*f(x,y(x))-16*f(x-dx,y(x-dx))+5*f(x-2*dx,y(x-2*dx)))

% pux initial data into vector
x(1) = x_0;
y(:,1) = y_0;

% I need to get y(x+dx) with local truncation error O(h^3).  I'll
% do this with Richardson extrapolation
F_now = feval(f,x(1),y(:,1));
% take one big step to reach y1
y_big = y(:,1) + dx*F_now;
% take two small steps to reach y3
y = y(:,1) + dx/2*F_now;
F = feval(f,x(1)+dx/2,y);
y_small = y + dx/2*F;
% use Richardson extrapolation
y(:,2) = 2*y_small - y_big;
x(2) = x_0 + dx;

% take a second-order accurate AB step to compute y(x+2*dx).  This
% will give local truncation error O(h^3)
x(3) = x_0 + 2*dx;
F_old = F_now;
F_now = feval(f,x(2),y(:,2));
y(:,3) = y(:,2) + dx/2*(3*F_now-F_old);

% now that I have the approximate solution at x_0, x_0+dx, and x_0+2*dx
% I can start with the Adams Bashforth.
for ii=3:N
  F_older = F_old;
  F_old = F_now;
  F_now = feval(f,x(ii),y(:,ii));
  y(:,ii+1) = y(:,ii) + dx/12*(23*F_now - 16*F_old+5*F_older);
  x(ii+1) = x_0 + ii*dx;
end




