f=input('give your input function to get root of.example:to give
f(x)=2x+5, write this way: @(x)2*x+5 \n') x0=input('give x0 value: \n') x1=input('give x1 value: \n') x2=input('give the x2 value: \n') error_limit=input('give your error limit value: \n') max_iteration=input('give the maximum iteration value: \n') iter =0; while (1) x3=((f(x0)*(x1*x1-x2*x2))+(f(x1)*(x2*x2-x0*x0))+... (f(x2)*(x0*x0-x1*x1)))/((2*f(x0)*(x1-x2)+... (2*f(x1)*(x2-x0))+(2*f(x2)*(x0-x1)))); error=(abs(x3-x2)/x3)*100; if error <= error_limit | iter >= max_iteration,break,end x0=x1; x1=x2;x2=x3; end fprintf('The result is: ') disp(x3)
GOLDEN SEARCH METHOD
f=input('put your function that you want to optimize:\n')
xl=input('put your lower limit:\n') xu=input('put your upper limit:\n') error_limit=input('put your error limit value:\n') max_iteration=input('put your maximum iteration value: \n') iteration=0; d=.618*(xu-xl); xa=xl+d; %xa lies in between xb and xu xb=xu-d; %xb lies in between xl and xa while(1) iteration=iteration+1; if f(xb)>f(xa) xopt=xb; error=(0.382*(xu-xl)/xopt)*100; xu=xa; xa=xb; xb=xu-0.618*(xu-xl); else xopt=xa; error=(0.382*(xu-xl)/xopt)*100; xl=xb; xb=xa; xa=xl+0.618*(xu-xl); end if error<error_limit||iteration>max_iteration, break ,end end disp(xopt)