工程数学实验二

function [x_opt, f_opt, iter] = steepest_descent()

    % 定义目标函数
    f = @(x) 100*(x(1)^2 - x(2))^2 + (x(1) - 1)^2;

    % 计算目标函数的梯度
    grad_f = @(x) [400*x(1)*(x(1)^2 - x(2)) + 2*(x(1) - 1); -200*(x(1)^2 - x(2))];

    % 定义终止准则
    epsilon = 1e-5;

    % 设置初始点
    x0_list = [0, 0; -1, 1; 2, -2]; % 可根据需要尝试不同的初始点

    for k = 1:size(x0_list, 1)
        % 初始化变量
        iter = 0;
        x_opt = x0_list(k, :)';
        f_opt = f(x_opt);
        grad_norm = norm(grad_f(x_opt));

        % 最速下降法迭代过程
        while grad_norm >= epsilon
            % 计算搜索方向
            p = -grad_f(x_opt);

            % 更新变量
            alpha = line_search(x_opt, p, f, grad_f);
            x_opt = x_opt + alpha * p;
            f_opt = f(x_opt);
            grad_norm = norm(grad_f(x_opt));

            % 更新迭代次数
            iter = iter + 1;
        end

        % 输出结果
        fprintf('初始点:%s\n', mat2str(x0_list(k, :)));
        fprintf('最优解:%s\n', mat2str(x_opt));
        fprintf('最优值:%f\n', f_opt);
        fprintf('迭代次数:%d\n', iter);
        disp('----------------------');
    end
end

function alpha = line_search(x, p, f, grad_f)
    % 简单的线搜索方法:固定步长
    alpha = 0.01;
end
% 调用最速下降法函数
[x_opt, f_opt, iter] = steepest_descent();

 

posted @ 2023-05-25 09:49  庞司令  阅读(17)  评论(0)    收藏  举报