function MathBookNewton()
% Illustrates how Newton's method can jump around before it
% converges.
close all
% Display MyF...
L = -1;
R = 12;
N = 500;
xVals = linspace(L,R);
yVals = MyF(xVals);
plot([L R],[0 0],'k',xVals,yVals)
axis([L R -1.5 1.5])
axis manual
set(gcf,'position',[100,200,800,600])
shg
title('MyF(x) = exp(-x/10).*sin(2*x)','fontsize',16)
xlabel('Click in a starting value','fontsize',16)
[xc,y] = ginput(1);
xlabel(' ')
hold on
% Display the starting value and the Newton step...
h1 = plot(xc,0,'.r','Markersize',25);
xNext = xc - MyF(xc)/derMyF(xc);
h2 = plot([xc xNext],[MyF(xc) 0],'k','linewidth',2);
h3 = plot(xNext,0,'.g','Markersize',25);
k=1;
pause
% Keep iterating as long as the iteration stays inside [L,R]
% and we have taken fewer than 5 steps...
while k<5 && L<=xNext && xNext<=R
delete(h1,h2,h3)
% Display the current iterate..
xc = xNext;
h1 = plot(xc,0,'.r','Markersize',25);
% Compute the next iterate and display the tangent line...
xNext = xc - MyF(xc)/derMyF(xc);
h2 = plot([xc xNext],[MyF(xc) 0],'k','linewidth',2);
h3 = plot(xNext,0,'.g','Markersize',25);
k = k+1;
pause
end
if xNext<L || xNext>R
xlabel('Out of bounds!','fontsize',16)
end

function y = MyF(x)
y = exp(-x/10).*sin(2*x);

function yp = derMyF(x)
yp = -exp(-x/10).*sin(2*x)/10 + 2*exp(-x/10).*cos(2*x);