% 此程序解决最优化方法中的黄金分割问题 % 目标函数Func() % 函数区间[a,b] % eps为目标区间长度 Func = @ (x) 2*x*x-5*x+1; a = 1; b = 6; eps = 1; i = 0; x1 = a+0.382*(b-a); x2 = a+0.618*(b-a); f1 = Func(x1); f2 = Func(x2); fprintf("i = %d\n",i); fprintf("a = %f b = %f\n",a,b); fprintf("x1 = %f x2 = %f\n",x1,x2); fprintf("f1 = %f f2 = %f\n",f1,f2); fprintf("abs(b-a) = %f\n",abs(b-a)); fprintf("\n") while 1 if(f1>f2) a=x1; elseif(f1==f2) a = x1; b = x2; else b = x2; end x1 = a+0.382*(b-a); x2 = a+0.618*(b-a); f1 = Func(x1); f2 = Func(x2); i=i+1; fprintf("i = %d\n",i); fprintf("a = %f b = %f\n",a,b); fprintf("x1 = %f x2 = %f\n",x1,x2); fprintf("f1 = %f f2 = %f\n",f1,f2); fprintf("abs(b-a) = %f\n",abs(b-a)); fprintf("\n") if(abs(b-a)<eps) break; end end x_res = 0.5*(a+b); f_res = Func(x_res); fprintf("x* = %f,f* = %f",x_res,f_res)
标签:f1,f2,黄金分割,fprintf,Matlab,Func,x2,x1,法求 From: https://www.cnblogs.com/sunworks/p/16797686.html