clear all; close all;
f = @(x) 100.*(x(2)-x(1).^2).^2+(1-x(1)).^2;
gradd = @(x) [200.*(x(2)-x(1).^2).*-2.*x(1)-2.*(1-x(1)) ...
    200.*(x(2)-x(1).^2)];
x0  = [1.2 1];x=x0;
a0 = 0.001;a=a0;
h = 10^-8;
h1 = [h 0]; h2 = [0 h];
fx = f(x);f0=fx+10;
k = 1;
while abs(fx-f0)>10^-16
    % grad f
    gf = imag([f(x+i*h1) f(x+i*h2)]/h);
    %gf = [f(x+h1)-f(x-h1)  f(x+h2)-f(x-h2)]/(2*h);
    f0 = fx;
    a=a0;
    prog=[1 1];
    ok = 0;
    while max(prog)>10^-12
        prog = -a.*gf;       
        xp   = x+prog;
        fxp  = f(xp);
        if fxp>fx
            a  = a/2;
        else
            ok = 1;
            fx =fxp;
            x  = xp;
        end
        fprintf('%d %20.15f %20.15f %20.15f %20.15f\n',k,x,fx,a)
    end
    if ok==0
       disp('line search failed - iteration stuck')
       break;
    end
    k = k + 1;
end

