% class2oct_show.m

% class2oct:  stuff done in class on 10/2, especially 
%             an easy newton and easy bisection example

format long g  % do "help format" to see some possible
               % styles for displaying numbers

disp('Newton to solve sin(x) = 0 to get x = pi:')
x = 3.0;
disp('      x_k               |x_k - pi|')
disp([x abs(x-pi)])
x = x - sin(x) / cos(x); disp([x abs(x-pi)])
x = x - sin(x) / cos(x); disp([x abs(x-pi)])
x = x - sin(x) / cos(x); disp([x abs(x-pi)])
x = x - sin(x) / cos(x); disp([x abs(x-pi)])
x = x - sin(x) / cos(x); disp([x abs(x-pi)])

disp('')
disp('again, but using a for loop:')
x = 3.0;
disp('      x_k               |x_k - pi|')
disp([x abs(x-pi)])
nerr=[abs(x-pi)];
for j=1:5
  x = x - sin(x) / cos(x); disp([x abs(x-pi)])
  nerr = [nerr abs(x-pi)];
end

% bisection for the same problem:  This requires decisions
%   to determine successive brackets.  This was done in class
%   "by-hand", meaning I decided by looking at the numbers.
%   Here is a loop with a conditional ("if") which does the same thing.
disp('')
disp('bisection, which gives successive brackets [a_k,b_k] with midpoints c_k:')
disp('      a_k               b_k                   |c_k - pi|')
bracket = [3 3.5];  % I have to start with a bracket [a, b] for
                    % which sin(a) is opposite in sign from sin(b)
berr = [];
for j=1:20
  mid = sum(bracket)/2;
  disp([bracket abs(mid-pi)]) % show bracket and accuracy of midpoint
  berr = [berr abs(mid-pi)];
  if sin(mid) * sin(bracket(1)) > 0  % true in the case where sin(mid) and sin(a)
                                     % agree in sign
    bracket(1) = mid;
  else
    bracket(2) = mid;
  end
end

% print command suited to Octave; note these lines inserted in .bashrc:
%    export GDFONTPATH="/usr/share/fonts/truetype/ttf-bitstream-vera"
%    export GNUPLOT_DEFAULT_GDFONT="Vera.ttf"
semilogy(1:6,nerr,'*',1:20,berr,'o','MarkerSize',10)
legend('Newton error','bisection error')
xlabel('iteration number','FontName','Vera','FontSize',14)
ylabel('|x_k - pi|','FontName','Vera','FontSize',14)
%print -depsc2 class2oct.eps
print -dpng class2oct.png

