This program implements the golden-section search algorithm. It locates the minimum or maximum of the function depending on the user’s preference, iterates until the relative error falls below a stooping criteria or exceeds an maximum number of iterations, return both the optimal x and f(x), minimizes the number of function evaluations.
r=(sqrt(5)-1)/2; %Golden Ratedisp('Number of max iteration')maxiter=input('maxiter= ');disp('Value of tolerance')tol=input('Tol= ');disp('For max enter "1", for min enter "0"')x=input('minmax= ');a=input('Lower bound= '); %Lower limitb=input('Upper bound= '); %Upper limitdisp(' ')disp('k x1 x2')for k=1:maxiterif (x==1) %Part that will find maxx1=a+r*(b-a); %First one of the points insidex2=b-r*(b-a); %Second one of the points insidefx1=-x1^4-2*x1^3-8*x1^2-5*x1; %Value of fx at first inside pointfx2=-x2^4-2*x2^3-8*x2^2-5*x2; %Value of fx at second inside pointif fx1>fx2 %Changing interval as [x2,b]a=x2;x2=x1;x1=a+r*(b-a);elseb=x1; %Changing interval as [a,x1]x1=x2;x2=b-r*(b-a);endfprintf ('%d %7.5f %7.5f\n', k,x1,x2)%Stop if the error is below toleranceif(abs((x1-x2)) endelse %Part that will find minx1=a+r*(b-a);x2=b-r*(b-a);fx1=3+6*x1+5*x1^2+3*x1^3+4*x1^4;fx2=3+6*x2+5*x2^2+3*x2^3+4*x2^4;if fx1 a=x2; %Changing interval as [x2,b]x2=x1;x1=a+r*(b-a);elseb=x1; %Changing interval as [a,x1]x1=x2;x2=b-r*(b-a);endfprintf ('%d %7.5f %7.5f\n', k,x1,x2)if(abs((x1-x2)) endendenddisp(' ')disp('Results')disp('x1 x2 f(x1) f(x2)')fprintf ('%7.5f %7.5f %7.5f %7.5f\n',x1,x2,fx1,fx2)