function [x_star fvertek iter] = nl_newton
%Newton-modszer, modositott Newton, szelomodszer, hurmodszer

%a program akkor all le, ha |f(x_n)| eleg kicsi, bar altalaban ennel jobb 
%leallasi kriterium az, ha |x_{n+1}-x_n| eleg kicsi.

f = @(x)(x.^3-x-2);
f_der = @(x)(3*x.^2-1);
hiba = 1e-06;
maxit = 50;
fvertek = zeros(1,4);

%Newton-modszer
x(1) = 2;
y = f(x(1));
it = 0;
while ((abs(y) > hiba) && (it < maxit))
    it = it + 1;
    x(it+1) = x(it) - f(x(it))/f_der(x(it));
    y = f(x(it+1));
end
x_star = zeros(length(x),4);
x_star(:,1) = x;
iter(1) = it;
fvertek(1) = y;
clear x y it


%szelomodszer - secant method
x(1) = 2;
x(2) = 1.2;
y = f(x(2));
it = 1;
while ((abs(y) > hiba) && (it < maxit))
    it = it + 1;
    x(it+1) = x(it) - f(x(it))/( (f(x(it))-f(x(it-1)))/(x(it)-x(it-1)));
    y = f(x(it+1));
end
x_star(1:length(x),2) = x;
iter(2) = it;
fvertek(2) = y;
clear x y it

%modositott Newton-modszer, 3 lepesenkent ertekeljuk ki a derivaltat
x(1) = 2;
y = f(x(1));
it = 0;
j = -2;
while ((abs(y) > hiba) && (it < maxit))
    it = it + 1;
    if (rem(it,3) == 1)
        j = j + 3;
        z = f_der(x(j));
    end
    x(it+1) = x(it) - f(x(it))/z;
    y = f(x(it+1));
end
x_star(1:length(x),3) = x;
iter(3) = it;
fvertek(3) = y;
clear x y j it

%hurmodszer - chord method
a = 1;
b = 2;
it = 0;
while (it < maxit)
    it = it + 1;
    c = a - f(a)/((f(b)-f(a))/(b-a));
    w(it) = c;      % w vektorba tesszuk el az osztopontokat
    y = f(c);
    if (abs(y) < hiba)
        break
    elseif (f(c)*f(b)<0)
        a = c;
    else
        b = c;
    end
end
x_star(1:length(w),4) = w;
iter(4) = it;
fvertek(4) = y;
clear x y w it