Código Python:
Ver original
deff('fx=ec(x)','fx=2*sin(x)-(x^2/10)'); xlow=0 xhigh=4 maxit=1000 es=0.000001 opcion=1 function [xopt,fopt,iter,ea]=goldmax(xlow,xhigh,maxit,fx) xl=xlow xh=xhigh iter=1 d=(xh-xl)*((sqrt(5)-1)/2*(xh-xl)) x1=xl+d x2=xh+d f1=ec(x1) f2=ec(x2) if f2<f1 then xopt=x1 fopt=f1 else xopt=x2 fopt=f2 end es=0.00001 ea=es*10 while ea>es & iter<maxit iter=iter+1 d=d*R if f1>f2 then xl=x2 x2=x1 x1=xl+d f2=f1 f1=ec(x1) else xh=x1 x1=x2 x2=xh-d f1=f2 f2=ec(x2) end if f1>f2 then xopt=x1 fopt=f1 else xopt=x2 fopt=f2 end if xopt~=0 ea=100*(1-R)*abs((xh-xl)/xopt) end end endfunction [xopt,fopt,iter,ea]=gold(xlow,xhigh,maxit,ec) disp(xopt)