Program for golden seleciton

sj_b 25 Feb 2018 23:32

```
Define LibPriv goldenselection(f,xl,xu,it)=
Func
:Local f,xl,xu,d,x1,x2,ea,es,i,it,xint,xopt,r1,r2
:Define f(x)=f
:Define es=0.001
:Define ea=1
:Define i=0
:Define d=(((1+√(5))/(2))-1)*(xu-xl)
:Define x1=xl+d
:Define x2=xu-d
:While it>i
: Define xint=xu-xl
: If f(1)<f(2) Then
: Define xopt=x1
: Define xl=x2
: Define x2=x1
: Define x1=xl+(((1+√(5))/(2))-1)*(xu-xl)
: Else
: Define xopt=x2
: Define xu=x1
: Define x1=x2
: Define x2=xu-(((1+√(5))/(2))-1)*(xu-xl)
: EndIf
: Define i=i+1
: Define ea=(2-((1+√(5))/(2)))*abs(((xint)/(xopt)))
:EndWhile
:Disp ea
:Disp xopt
:Disp i
:EndFunc
```

Ported matlab code

```
function GS = goldenselection2(gs,xl,xu,it)
syms x
gs(x)=gs
es=0.0001;
ea=1;
i=0;
d=(((1+sqrt(5))/(2))-1)*(xu-xl);
x1=xl+d;
x2=xu-d;
while it>i
xint=xu-xl;
if gs(x1)<gs(x2)
xopt=x1;
xl=x2;
x2=x1;
x1=xl+(((1+sqrt(5))/(2))-1)*(xu-xl);
else
xopt=x2;
xu=x1;
x1=x2;
x2=xu-(((1+sqrt(5))/(2))-1)*(xu-xl);
end
i=i+1;
ea=(2-(((1+sqrt(5))/(2))))*abs(((xint)/(xopt)))*100;
end
fprintf('ea %f\n',ea)
fprintf('xopt %f\n',xopt)
fprintf('iterations %f\n',i)
end
```

[Posts Merged by Moderator]