revisenewton.m
syms x1 x2 x3 xx;
% f = x1*x1 +x2*x2 -x1*x2 -10*x1 -4*x2 + 60 ; % f = x1^2 + 2*x2^2 - 2*x1 *x2 -4*x1 ;
f = 100 * (x1^2 - x2^2) + (x1 -1 )^2 ;
hessen = jacobian(jacobian(f , [x1,x2]),[x1,x2]) ; gradd = jacobian(f , [x1,x2]) ;
X0 = [0,0]' ;
B = gradd' ;
x1 = X0(1);
x2 = X0(2);
A = eval(gradd) ;
% while sqrt( A(1)^2 + A(2)^2) >0.1
i=0;
while norm(A) >0.1
i = i+1 ;
fprintf('the number of iterations is: %d\n', i)
if i>10
break;
end
B1 = inv(hessen)* B ;
B2= eval(B1);
% X1 = X0 - B2
% X0 = X1 ;
f1= x1 + xx * B2(1);
f2= x2 + xx* B2(2);
% ff = norm(BB) ?
syms x1 x2 ;
fT=[subs(gradd(1),x1,f1),subs(gradd(2),x2,f2)];
ff = sqrt((fT(1))^2+(fT(2))^2);
MinData = GoldData(ff,0,1,0.01);
x1 = X0(1);
x2 = X0(2);
x1 = x1 + MinData * B2(1)
x2 = x2 + MinData * B2(2)
A = eval(gradd)
End
GoldData.m
function MiniData = GoldData( f,x0,h0,eps) syms xx;
if nargin==3
eps=1.0e-6;
end
[minx,maxx]=minJT(f,x0,h0,eps);
MiniData = Gold(f,minx,maxx,0.001 ) ;
minJT.m
function [minx,maxx]=minJT(f,x0,h0,eps)
%目标函数:f;
%初始点:x0;
%初始步长:h0;
%精度:eps;
%目标函数取包含极值的区间左端点:minx; %目标函数取包含极值的区间又端点:maxx; syms xx;
format long;
if nargin==3
eps=1.0e-6;
end
x1=x0;
k=0;
h=h0;
while 1
x4=x1+h; %试探步
k=k+1;
% f4=subs(f,findsym(f),x4);
% f1=subs(f,findsym(f),x1);
xx =x4;
f4 = eval(f);
xx=x1;
f1 = eval(f);
if f4<f1
x2=x1;
x1=x4;
f2=f1;
f1=f4;
h=2*h; %加大步长
else
if k==1
h=-h; %反向搜索
x2=x4;
f2=f4;
else
x3=x2;
x2=x1;
x1=x4;
break;
end
end
end
minx=min(x1,x3);
maxx=x1+x3-minx;
format short;
Gold.m
function Mini=Gold(f,a0,b0,eps) syms x;format long;
syms xx;
u=a0+0.382*(b0-a0);
v=a0+0.618*(b0-a0);
k=0;
a=a0;b=b0;
array(k+1,1)=a;array(k+1,2)=b; while((b-a)/(b0-a0)>=eps)
Fu=subs(f,xx,u);
Fv=subs(f,xx,v);
if(Fu<=Fv)
b=v;
v=u;
u=a+0.382*(b-a);
k=k+1;
elseif(Fu>Fv)
a=u;
u=v;
v=a+0.618*(b-a);
k=k+1;
end
array(k+1,1)=a;array(k+1,2)=b; end
xx
Mini=(a+b)/2;。