close all;

tolerance = 10e-15;

fun = @(x)x - cos(x);

% definition av intervalet [n,p]

n= -1;
p=1;
it=0;


% Halveringsmetoden

	  while abs(n - p) > tolerance
m = (n + p)/2;
         if fun(m) < 0 
  n = m;
         else
	   p = m;
        end

	it = it+1;

func_val(it) = fun(p);


iteration(it) = it;
end

	
figure

plot(iteration,  func_val,'o r-',  'LineWidth',2)
 xlabel('iteration')
  ylabel(' x^k -  cos(x^k)')
 legend('Halveringsmetoden');
title(['Halveringsmetoden, konvergens (iterations):',num2str(it)]);

%Sekantmetoden

x=0;
iteration_sekant = 0;
func_sekant = 0;
error_sekant = 0;

k=2;
%Initialiseringen
x(1) = 0;
x(2) = 0.1;


iteration_sekant(1) = 1;
iteration_sekant(2) = 2;
func_sekant(1) =fun(x(1));
func_sekant(2) =fun(x(2));

while  abs(x(k) - x(k-1)) > tolerance

numerator =  fun(x(k))*(x(k-1) - x(k));
denominator = fun(x(k-1)) - fun(x(k));

x(k+1) = x(k) - numerator/denominator;

k = k+1;
  iteration_sekant(k) = k;
func_sekant(k) =fun(x(k));



end


 % hold on
figure
plot(iteration_sekant,func_sekant, 'o b-',  'LineWidth',2)
 xlabel('iteration')
  ylabel('  cos(x^k)')
 legend('Sekantmetoden');
title(['Sekantmetoden, konvergens (iterations):',num2str(k)]);


% Newtons metod

y=0;
iteration_newton = 0;
func_newton = 0;


%Initialiseringen
y(1) = 1.0;
k=2;

iteration_newton(1) = 1;
func_newton(1) =fun(y(1));

numerator =  fun(y(1));
denominator = 1 + sin(y(1));
y(2) = y(1) - numerator/denominator;
  
% Main Newton's iterations  
while abs( y(k) - y(k-1) ) > tolerance

numerator =  fun(y(k));
denominator = 1 + sin(y(k));
y(k+1) = y(k) - numerator/denominator;
iteration_newton(k) = k;
func_newton(k) =fun(y(k));

k = k+1;

if k == 2000
break
end
  end

figure
  plot(iteration_newton,func_newton, 'o b-','LineWidth',2)

  
  xlabel('iteration')
  ylabel(' cos(x^k)')
%  legend('Halveringsmetoden','Sekantmetoden','Newtons metod')
%  title(['Sekant, halvering  och Newton  för x(1)=',num2str(x(1)),', x(2)= ',num2str(x(2))])
 legend('Newtonsmetod ');
 title(['Newtonsmetod, konvergens (iterations):',num2str(k)])

iteration

 iteration_sekant

 iteration_newton

p

x

y
