% GoldenSection.m
% Script to run example 6.8 in Heath's book.
% K. Ming Leung. 05/06/03

clear all; 
format compact;
exactAnswer = 1/sqrt(2);
fcn = 'fcn6p8';
a = 0; b = 2; tol = 1e-4;
tau = 0.5*(sqrt(5)-1); tau1 = 1-tau;
L = b-a; 
x1 = a + tau1*L;
f1 = feval(fcn,x1);
x2 = a + tau*L;
f2 = feval(fcn,x2);

fprintf('\n');
fprintf(' -------------------------------------------\n');
fprintf(1,'     x1        f(x1)       x2        f(x2)\n');
fprintf(' -------------------------------------------\n');
fprintf(1,'%10.6f %10.6f %10.6f %10.6f\n',x1, f1, x2, f2);

while ((b-a)>tol)
    if (f1>f2)
        a = x1; 
        x1 = x2;
        f1 = f2;
        x2 = tau1*a + tau*b;
        f2 =feval(fcn,x2);
    else
        b = x2; 
        x2 = x1;
        f2 = f1;
        x1 = tau*a + tau1*b;
        f1 = feval(fcn,x1);
    end
    fprintf(1,'%10.6f %10.6f %10.6f %10.6f\n',x1, f1, x2, f2);
end

format long g;
exactAnswer, fcnMin = feval(fcn,exactAnswer)