% 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)])
for j=1:5
  x = x - sin(x) / cos(x); disp([x 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)
for j=1:20
  mid = sum(bracket)/2;
  disp([bracket abs(mid-pi)]) % show bracket and accuracy of midpoint
  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

