工程数学实验
1. 算法步骤
黄金分割法也叫0.618法,是一种基于区间收缩的极小值搜索算法。
比如以 [ a , b ] [a,b][a,b] 为区间,产生两个内点
x 1 = a + 0.382 ∗ ( b − a ) x 2 = a + 0.618 ∗ ( b − a ) x_1 = a + 0.382*(b-a)\\ x_2 = a + 0.618*(b-a)
x
1
=a+0.382∗(b−a)
x
2
=a+0.618∗(b−a)
然后根据 f ( x 1 ) , f ( x 2 ) f(x_1),f(x_2)f(x
1
),f(x
2
) 的大小进行区间更新:
如果 f ( x 1 ) < f ( x 2 ) f(x_1)<f(x_2)f(x
1
)<f(x
2
),区间变为 [ x 1 , b ] [x_1,b][x
1
,b]
如果 f ( x 1 ) > f ( x 2 ) f(x_1)>f(x_2)f(x
1
)>f(x
2
),区间变为 [ a , x 2 ] [a,x_2][a,x
2
]
2. 代码
封装好的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);
标签:xm,日报,fx1,数学,alList,x2,fprintf,x1 From: https://www.cnblogs.com/yankeqi/p/17470988.html