% explicit Euler time stepping example 12.3 from Suli/Mayers
% Note that in the book the sign of g is incorrect
f = @(x,y) y.^2-(x.^4-6*x.^3+12*x.^2-14*x+9)/((1+x).^2);
exact_y= @(x) (1-x).*(2-x)./(1+x);
x0 = 0;
y0 = 2;
% number of steps
N = 20;
% final time
T = 2;
% time step size
h = T/N;

X = zeros(1,N+1);
xk = x0;
Y = zeros(1,N+1);
yk = y0;
Y(1) = y0;
for k=1:N
   xk = x0 + (k-1)*h;
   yk = yk + h*f(xk,yk);
   % keep record for plotting
   X(k) = xk;
   Y(k+1) = yk;
end

X(N+1) = x0 + N*h;
plot(X,Y,'r-o','linewidth', 2); hold on
Xfine = linspace(0,T,200);
plot(Xfine,exact_y(Xfine),'b','linewidth', 2)