梯度下降-牛顿法 解多元非线性方程组
clear;clc format; x0=[0 100 0 0]; % 迭代初始值 eps = 0.00001; % 定位精度要求 for i = 1:20 f = double(subs(fun(x0),{'x1' 'x2' 'x3' 'x4'},{x0(1) x0(2) x0(3) x0(4)}));%方程个数改变之后这里需要改个数 f df = double(subs(dfun(x0),{'x1' 'x2' 'x3' 'x4'},{x0(1) x0(2) x0(3) x0(4)})); %方程个数改变之后这里需要改个数 x = x0 - f/df; if(abs(x-x0) < eps) break; end x0 = x; % 更新迭代结果 end x0(3)=x0(3)*0.85 x0(4)=x0(4)*0.3 disp('定位坐标:'); x0 disp('迭代次数:'); i
x0 = [-10 105 0 0.8]; h = 1e-4; eps = 1e-6; m = length(x0); x0 = transpose(x0); n = 1; tol = 1; for j = 1:10 fx= double(subs(fun(x0),{'x1' 'x2' 'x3' 'x4'},{x0(1) x0(2) x0(3) x0(4)}));%方程个数改变之后这里需要改个数 fx=transpose(fx); J = zeros(m, m); for i = 1: m x1 = x0; x1(i) = x1(i) + h; f1=double(subs(fun(x1),{'x1' 'x2' 'x3' 'x4'},{x1(1) x1(2) x1(3) x1(4)}));%方程个数改变之后这里需要改个数 f1=transpose(f1); J(:,i) = (f1 - fx)/h; end lamda = fx/sum(diag(transpose(J) * J)); r = x0 - J*lamda; fr = double(subs(fun(r),{'x1' 'x2' 'x3' 'x4'},{r(1) r(2) r(3) r(4)}));%方程个数改变之后这里需要改个数 tol = dot(fr, fr); x0 = r; end x0(3)=x0(3)*0.85 x0(4)=x0(4)*0.3 disp('定位坐标:'); x0 disp('迭代次数:'); j
function df = dfun(x) %UNTITLED 此处显示有关此函数的摘要 % 此处显示详细说明 f=fun(x); df=[diff(f,'x1');diff(f,'x2');diff(f,'x3');diff(f,'x4')]; %方程个数修改之后这里需要增加或减少:diff(f,'xn') end
function f = fun(x) %UNTITLED 此处显示有关此函数的摘要 % 此处显示详细说明 syms x1 x2 x3 x4 %这里面是变量个数,如果有4个方程就写到x4 f1=exp(-100+2*x1+x2)-0.85 * x3^2; f2=exp(-200+x1+2*x2)-0.3 * x4^2; f3=x3+x4-1; f4=2*x3+x4^2-1;%以上四行分别是是四个函数 f=[f1,f2,f3,f4]% %方程个数修改之后这里需要增加或减少:fn end