1. 程式人生 > >Matlab學習手記——非線性方程組求解:牛頓下山法

Matlab學習手記——非線性方程組求解:牛頓下山法

功能:牛頓下山法求解非線性方程組。

  • 牛頓下山法
function [x, n] = NonLinearEquations_NewtonDown(x0, err)
%{
函式功能:牛頓下山法求解非線性方程組的解;
輸入:
  x0:初始值;
  err:精度閾值;
輸出:
  x:近似解;
  n:迭代次數;
示例:
clear; clc;
[r, n] = NonLinearEquations_NewtonDown([0 0 0], 1e-6)
%} 
% = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
x = x0- myfun(x0)/dmyfun(x0);
n = 1;
tol = 1;
while tol > err
    x0 = x;
    tol = 1;
    w=1;
    F1 = norm(myfun(x0));
    while tol >= 0
        x = x0 - w*myfun(x0)/dmyfun(x0);
        tol = norm(myfun(x)) - F1;
        w = w/2;
    end
    tol = norm(x - x0);
    n = n + 1;
    if(n > 1000)
        disp('迭代步數太多,可能不收斂!');
        return;
    end
end

function f = myfun(x)
x1 = x(1);
x2 = x(2);
x3 = x(3);
f(1) = 3*x1 - cos(x2*x3) -1/2;
f(2) = x1^2 - 81*(x2 + 0.1) + sin(x3) + 1.06;
f(3) = exp(-x1*x2) + 20*x3 + 1/3*(10*pi - 3);

function df =dmyfun(x)
x1 = x(1);
x2 = x(2);
x3 = x(3);
df=[3, x3*sin(x2*x3), x2*sin(x2*x3); 2*x1, -81, cos(x3); -x2*exp(-x1*x2), -x1*exp(-x1*x2), 20];