%% illustrates how Newton's method works

% f(x) evaluated between -5 and 5
x = linspace(-5, 5);
y = x .* x - 1;

% Newton's method
x0 = 4;
epsilon = 1e-9;
[root, xvals] = newton(x0, epsilon);

for index = 1:(length(xvals) - 1)
   figure
   xi = xvals(index);
   yi = xi * xi - 1;
   yiPrime = 2 * xi;
   
   % plot f(x)
   plot(x, y, 'c');
   axis([-5 5 -10 30])
   
   hold on
   % plot the tangent line at f(xi)
   yt = yiPrime * (x - xi) + yi;
   plot(x, yt, 'r-');
   legend('f(x)', 'tangent line at f(x)');
   
   % add some markers and text
   plot(xi, 0, 'ko', 'MarkerFaceColor', 'k');
   text(xi, -2, 'x_i');
   plot(xi, yi, 'ko', 'MarkerFaceColor', 'k');
   text(xi - 0.2, yi + 2, 'f(x_i)');
   
   % connect the markers with a line
   line([xi xi], [0 yi], 'Color', 'k');
   
   % show that the next estimate is the
   % x-intercept of the tangent line
   xj = xvals(index + 1);
   plot(xj, 0, 'ro');
   text(xj, -3, 'x_{i + 1}');
   
   % draw the x and y axes
   line(xlim, [0 0], 'Color', 'k');
   line([0 0], ylim, 'Color', 'k');
end