function main()
clear all;clc
%% the original conditions 原始的条件
f=@(x)exp(-x)+x^2;
a=0;
b=1;
Theta_error=0.15;
%% execute FibonacciOpt Algorithm 执行FibonacciOpt算法
[x_opt,f_opt,stepNum]=FibonacciOpt(f,a,b,Theta_error);
%% compute Fn and the step numbers 计算Fn和步长
Fn=(b-a)/Theta_error;%%Fn=20/3
x=[];
x(1)=1;
x(2)=1;
i=1;
while x(i)<Fn
x(i+2)=x(i)+x(i+1);
i=i+1;
end
N=i;
%% the Opt Algorithm 选择算法
a1=x(N-2)/x(N)*(b-a)+a;
a2=x(N-1)/x(N)*(b-a)+a;
for i=1:N-3
f1=feval(f,a1);%%feval函数又叫评价函数,feval是把已知的数据或符号带入到一个定义好的函数句柄中
f2=feval(f,a2);
if f1>f2
a=a1;
a1=a2;
f1=f2;
%%f1=f2;
%%a1=a2;
a2=a+x(N-i-1)/x(N-i)*(b-a);
else
b=a2;
a2=a1;
f2=f1;
a1=a+x(N-i-2)/x(N-i)*(b-a);
end
stepNum=i;%%即a1=a2时得出结果
end
x_opt=(a+b)/2;
f_opt=feval(f,x_opt);
stepNum=stepNum+1;
%% function figure 函数图
x=a:0.01:b;
y=exp(-x)+x.^2;
plot(x,y,'k')
hold on
plot(x_opt,f_opt,'r*')
fprintf('%d is the optimal point of the function and execute %d steps',x_opt,stepNum)
评论0