# function % focuses on narrower interval [x,b] x1

function mmin,mmax = Programming3(a,b,epsilon,f)% Performs golden section search on the function f, which needs to be% input, along with the initiall interval and desired precisiona1 = a;                                 % store input permanentlyb1 = b;                                 % store input permanentlyif f(a+epsilon/2) > f(a)                % tests to see if f has a min or max    if f( b-epsilon/2) < f(b)        fprintf('Function is increasing with min at a and max at b ');        mmin = a; mmax = b; return;    end  %tests to if mode is at endpoint    d=-1;else    if f( b-epsilon/2) > f(b)        fprintf(‘Function is decreasing with max at a and min at b
‘);        mmax = a; mmin = b; return;    end    d=1;endc = (-1+sqrt(5))/2;     % define necessary constants and starting variablesx1 = c*a + (1-c)*b; fx1 = d*f(x1);x2 = (1-c)*a + c*b; fx2 = d*f(x2); N=50;fprintf(‘——————————————————
‘);fprintf(‘     x1         x2        f(x1)      f(x2)      b – a
‘);fprintf(‘——————————————————
‘)fprintf(‘%.4e %.4e %.4e %.4e %.4e
‘, x1, x2, d*fx1, d*fx2, b-a);for i = 1:N   if fx1 < fx2      b = x2;                       % focuses on narrower interval a,y      x2 = x1;      fx2 = fx1;      x1 = c*a + (1-c)*b;           % calculates new point in subinterval      fx1 = d*f(x1);                % evaluates function at new point   elseif fx1 > fx2      a = x1;                       % focuses on narrower interval x,b      x1 = x2;      fx1 = fx2;      x2 = a*(1-c) + c*b;           % calculates new point in subinterval      fx2 = d*f(x2);                % evaluates function at new point   else         a=x1; b=x2;       x1 = c*a + (1-c)*b;        x2 = (1-c)*a + c*b;       fx1 = d*f(x1);        fx2 = d*f(x2);    end                             % finished iteration, now prints value                                    % of iteration and tests if should stop fprintf(‘%.4e %.4e %.4e %.4e %.4e
‘, x1, x2, d*fx1, d*fx2, b-a);    if (abs(b-a) < 2*epsilon)        fprintf('succeeded after %d steps ', i)        fprintf('The mode is %d ',(a+b)/2)         r = (a+b)/2;        if and(f(r) > f(a1), f(r) > f(b1))   % testing to see if min or max            mmax = r;            if f(a1) > f(b1)                mmin = b1;            else                 mmin = a1;            end        elseif and(f(r) < f(a1), f(r) < f(b1))            mmin = r;            if f(a1) > f(b1)                mmax = a1;            else                 mmax = b1;            end        end         return    end  endfprintf(‘failed after %d steps
‘, N);