% gss.m -- Golden Section Search
% Written Oct 19, 2007 by Eric Olson for Math/CS 466/666
%
% For more information see Chapter 7.1 in Numerical Analysis and
% Scientific Computation by Jeffery J. Leader

function x=gss(f,a,b,c)
%   b=a+2/(3+sqrt(5))*(c-a);
    fa=feval(f,a);
    fb=feval(f,b);
    fc=feval(f,c);
    if (fa>fb || fc>fb)
        disp('bad starting bracket');
        x=nan; return
    end
    for i=1:100
        d=b+(-1+sqrt(5))/(3+sqrt(5))*(c-a);
%       disp(sprintf('[%g,%g,%g,%g]',a,b,d,c));
        fd=feval(f,d);
        L=abs(c-a);
        if (fa<=fb && fd<=fb)
%           disp('L1 is good!');
            c=a; a=d; fc=fa; fa=fd;
        else
%       if (fb<=fd && fc<=fd)
%            disp('L2 is good!');
            a=b; b=d; fa=fb; fb=fd;
        end
        disp(sprintf('ratio=%g',abs(c-a)/L));
        if(abs(a-c)<(1.0e-8)*max(abs(a),abs(c)))
            x=b+(-1+sqrt(5))/(3+sqrt(5))*(c-a);
            return
        end
    end
    disp('failed to meet tolerance');
    x=nan;
