工程数学 上机实验一
封装好的golds函数:
function [xm,fm,aList,bList,alList,akList] = golds(f,a,b,tol)
% f: 待优化的目标函数
% a,b: 初始区间
% tol: 精度要求
% xm,fm: 最优解和相应的最优函数值
% 黄金分割比例
r = (sqrt(5)-1)/2;
% 初始值
L = b-a;
x1 = a + (1-r)*L;
x2 = a + r*L;
fx1 = f(x1);
fx2 = f(x2);
% 记录每次迭代的值
i = 1;
aList(i) = a;
bList(i) = b;
alList(i) = x1;
akList(i) = x2;
% 迭代计算
while L > tol
if fx1 > fx2
a = x1;
x1 = x2;
fx1 = fx2;
x2 = a + r*(b-a);
fx2 = f(x2);
else
b = x2;
x2 = x1;
fx2 = fx1;
x1 = a + (1-r)*(b-a);
fx1 = f(x1);
end
i = i+1;
aList(i) = a;
bList(i) = b;
alList(i) = x1;
akList(i) = x2;
L = b-a;
end
% 输出结果
xm = (a+b)/2;
fm = f(xm);
end
然后调用 golds 函数:
% 定义函数
f = @(x) x^2 - sin(x);
% 定义区间和精度
a = 0; b = 1; tol = 1e-6;
% 调用 golds 函数求解
[xm,fm,aList,bList,alList,akList] = golds(f,a,b,tol);
% 输出结果
fprintf('The minimum point is %f, and the minimum value is %f.\n', xm, fm);
fprintf('The a values are:\n'); disp(aList);
fprintf('The b values are:\n'); disp(bList);
fprintf('The al values are:\n'); disp(alList);
fprintf('The ak values are:\n'); disp(akList);

浙公网安备 33010602011771号