You are on page 1of 4

ABDURRASHID ALI TIFFI

BU/17A/ENG/2538
Advance Computer Programming & Statistics (503)
Golden section search

Golden section code

%Function: A function to perform golden section search


%Input: Function - fn, initial_step, and minimun width
%Output : The final bracket, evolution of the brackets
function [a, b, c] = Golden_section(fn, x0, i_step,
min_width)

if (2*i_step < min_width)


disp ('A minimun width is required please');
return;
end
% Take the first step
f_init = fn(x0);
f_step = fn(x0 + i_step);

%Find the direction of search

if (f_init < f_step)


a = x0 + i_step;
b = x0;
c = x0 - i_step;
i_step = -i_step;
else
a = x0;
b = x0 + i_step;
c = b + i_step;
end

% Determine the initial bracket


while(fn(c) < fn(b))
a = b;
b = c;
c = c + i_step;
end
% Make a,b,c are in ascending order whether stepping
uphill or
% downhill
if (c < a)
swap = a;
a = c;
c = swap;
end
%Start the ploting process
a_start = a;
c_start = c;

figure();
r = 0;
plot ([a,b,c], [r,r,r], 'b-x');
hold on;
r = r + 0.25;
gold = (3 - sqrt(5)) /2;

% Do a golden search
while (abs(c - a) >= min_width)

%Find the largest interval of the golden section and


use it
if ((c - b) > (b - a))
x = b + gold*(c - b);
else
x = a + gold*(b - a);
end
if (x < b)
if (fn(x) < fn(b))
c = b;
b = x;
else
a = x;
end
elseif (x > b)
if (fn(x) < fn(b))
a = b;
b = x;
else
c = x;
end
else
disp('Cannot insert new input');
break;
end

%Plotting graph

plot([a,b,c], [r,r,r], 'b-x');


hold on;
r = r + 0.25;
end

Code for equation1 (@my_func2)

%Equation 1 for Golden section


function fb= my_func2 (x) % %x=my_function test function for
minimisation

fb = x^2 + exp(-abs(x-4));

Output for (@my_func2)

>>Golden_section (@my_func2, 1, 1, 0.01)

ans =

-0.0132
Figure 1 Golden_section(@my_func2,1 , 1, 0.01)

Code for equation2 (@my_func3)

%Equation 2
function fc = my_func3 (x) %my_function test function for
minimisation

fc = (x-3)^2 + log(1 + abs (x));

Output for (@my_func2)

>> Golden_section (@my_func3, 1, 1, 0.01)

ans =

2.8673
Figure 2Golden_section(@my_func3,1 , 1, 0.01)

You might also like