 %% NEWTON'S METHOD via a WHILE LOOP: 
%(Selcuk Bayin, METU-NCC, bayin@metu.edu.tr)
clc
disp('EX 1:   Solve 0 = x.^6 + 2*x.^5 - 3*x.^4 - 10*x.^3 - 6*x.^2 + 8*x + 8')
%Function
f = inline('x.^6 + 2*x.^5 - 3*x.^4 - 10*x.^3 - 6*x.^2 + 8*x + 8', 'x')    
%Derivative
df = inline('6*x.^5 + 10*x.^4 - 12*x.^3 - 30*x.^2 - 12*x + 8', 'x')         
%%
clc
fprintf('--------\nInitial guess:')
%To find appropriate guesses see plotForNewton3
%Thus we use x=-2.5 and x=-1.5, x=1.5 and x=3 as our guesses
%Root1
x = -2.5
iteration=0;
while ((iteration < 1000) && (abs(f(x)) > .00001))
    x = x - f(x)./df(x); 
    iteration = iteration + 1;
end
disp('R00T 1:')
disp('       x      error   iteration')
disp([x, abs(f(x)), iteration])
%%
%Root2
clc
fprintf('--------\nInitial guess:')
x = -1.5
iteration=0;
while ((iteration <500) && (abs(f(x)) > .00001))
    x = x - f(x)./df(x); 
    iteration = iteration + 1;
end
disp('ROOT 2:')
disp('       x      error   iteration')
disp([x, abs(f(x)),iteration])
%%
%Root3
clc
fprintf('--------\nInitial guess:')
x = 1.5
iteration=0;
while ((iteration <500) && (abs(f(x)) > .00001))
    x = x - f(x)./df(x); 
    iteration = iteration + 1;
end
disp('ROOT 3:')
disp('       x      error   iteration')
disp([x, abs(f(x)),iteration])
%%
%Root4
clc
fprintf('--------\nInitial guess:')
x = 3
iteration=0;
while ((iteration <500) && (abs(f(x)) > .00001))
    x = x - f(x)./df(x); 
    iteration = iteration + 1;
end
disp('ROOT 4:')
disp('       x      error   iteration')
disp([x, abs(f(x)),iteration])

disp('-----------------------')
 



