% HW 3 Problem 3
% SAMPLE CODE - TO BE MODIFIED
% Assumes the following have been implemented:
%  - polynm.m - Newton's method specialized  to polynomials
%  - horner.m - Horner's method to deflate a polynomial
%  - hornernm.m - Horner's method specialized to 
%                 find value + derivative at a point
%                 (used internally in polynm.m)
tol = 1e-5;
maxit = 20;
format long

% This defines the polynomial 
% p(z) = z^4 + 2 z^2 - z -3
p = [1,0,2,-1,-3];

%  try starting at z0 = 1
z0=1;
[r1,k]=polynm(p,z0,tol,maxit);
fprintf('found root r1 = %g in %d iterations\n',r1,k);

%  try starting at z0 = 0
z0=0;
[r2,k]=polynm(p,z0,tol,maxit);
fprintf('found root r2 = %g in %d iterations\n',r2,k);

% deflate polynomial
[q1,r] = horner(p,r1);
[q2,r] = horner(q1,r2);

fprintf('deflated polynomial is:\n');
disp(q2)

fprintf('with roots:\n');
% TO BE CHANGED: use QUADRATIC FORMULA instead of Matlab's ROOTS
disp(roots(q2)) 

% compare to the roots that Matlab finds:
fprintf('the roots according to Matlab are:\n');
disp(sort(roots(p)));

% Note: the sort command works even with complex numbers, it is used
% here to order roots so that different methods can be compared more
% easily

% Sample output:
%
%  >> prob3_sample                     
%  found root r1 = 1.12412 in 4 iterations
%  found root r2 = -0.876053 in 8 iterations
%  deflated polynomial is:
%     1.000000000000000   0.248069913842867   3.046330164938122
%  
%  with roots:
%   -0.124034956921434 + 1.740961083539670i
%   -0.124034956921434 - 1.740961083539670i
%  
%  the roots according to Matlab are:
%   -0.876053115817114                     
%    1.124123029704315                     
%   -0.124034956943601 - 1.740961083530082i
%   -0.124034956943601 + 1.740961083530082i
%  
