5/6日总结

今天完成了数学建模实验1,黄金分割法求极小值
主函数:
% 主函数
% 定义目标函数
phi = @(x) x.^2 - x + 6;

% 设置进退法的初始参数
x0 = 0; % 起始点
h = 0.1; % 初始步长

% 设置精度要求
epsilon = 1e-6;

% 调用golds函数
[s, phis, k, G, E] = golds(phi, x0, h, epsilon);

% 输出每次迭代的a、b、a_l(p)、a_k(q)的值
fprintf('迭代过程记录:\n');
fprintf('迭代次数\t a\t b\t a_l(p)\t a_k(q)\n');
for i = 1:k
fprintf('%d\t %.6f\t %.6f\t %.6f\t %.6f\n', i, G(i, 1), G(i, 4), G(i, 2), G(i, 3));
end
函数:
% 输出最终结果
fprintf('\n最终结果:\n');
fprintf('近似极小点 s = %.6f\n', s);
fprintf('极小值 phis = %.6f\n', phis);
function [s, phis, k, G, E] = golds(phi, x0, h, epsilon)
% 输入: phi 是目标函数,x0 是进退法起始点,h 是进退法初始步长,epsilon 分别是自变量和函数值的容许误差
% 输出: s, phis 分别是近似极小点和极小值,G 是 nx4 矩阵。其第 k 行分别是 a, p, q, b 的第 k 次迭代值
% [ak, pk, qk, bk],E = [ds, dphi],分别是 s 和 phis 的误差限
% 进退法确定初始区间
x1 = x0;
f1 = feval(phi, x1);
x2 = x1 + h;
f2 = feval(phi, x2);
if (f2 < f1)
h = 2h;
x1 = x2;
f1 = f2;
x2 = x1 + h;
f2 = feval(phi, x2);
while (f2 < f1)
h = 2
h;
x1 = x2;
f1 = f2;
x2 = x1 + h;
f2 = feval(phi, x2);
end
a = x1;
b = x2;
else
h = -h;
x2 = x1;
f2 = f1;
x1 = x2 + h;
f1 = feval(phi, x1);
while (f1 < f2)
h = 2h;
x2 = x1;
f2 = f1;
x1 = x2 + h;
f1 = feval(phi, x1);
end
a = x2;
b = x1;
end
delta = 1e-6; % 根据精度要求设置自变量误差限
t = (sqrt(5) - 1)/2; h = b - a;
phia = feval(phi, a); phib = feval(phi, b);
p = a + (1 - t)
h; q = a + th;
phip = feval(phi, p); phiq = feval(phi, q); k = 1; G(k, 😃 = [a, p, q, b, h];
while (h > delta)
if (phip < phiq)
b = q; phib = phiq; q = p; phiq = phip;
h = b - a; p = a + (1 - t)
h; phip = feval(phi, p);
else
a = p; phia = phip; p = q; phip = phiq;
h = b - a; q = a + t*h; phiq = feval(phi, q);
end
k = k + 1; G(k, 😃 = [a, p, q, b, h];
end
ds = abs(b - a); dphi = abs(phib - phia);
if (phip <= phiq)
s = p; phis = phip;
else
s = q; phis = phiq;
end
E = [ds, dphi];
end

posted @ 2025-05-06 23:34  离璨霂  阅读(20)  评论(0)    收藏  举报