Control Structures

5628

counter=0;
counterMax=12;
t=0.0;
TMax=12.3;
h=2.3;

While[
And[t≤ TMax,counter++<counterMax],
t=t+h;
Print["counter=",counter, " t=", t]
]

5630

Planning:
1) counter and counterMax are safegaurds for spinning out of control.  Counts and controls the maximum number of steps;
2) Delfk is the value of the gradient of the objective function f at the current iteration xk
3) f,  Df,  DDf are the function, gradient amd second gradient of the objective function

Clear[f,x,y,Df, DDF]
ϵ=0.01;
f[{x_,y_}]:=  2.0(((x + 3.0 y))^2)+ x-y +(((x - 1.3 y))^2) + ϵ Sin[x y];
Df[{x_,y_}]=Simplify[D[f[{x,y}],{{x,y}}]];
DDf[{x_,y_}]=Simplify[D[Df[{x,y}],{{x,y}}]];

Clear[NewtonStep,NewtonStep]
NewtonStep[xk_,Delfk_ ,{Df_,DDf_}]:= Module[
{Newxk, NewDelk,α,p},
p=-LinearSolve[DDf[xk], Delfk];
α=1;
Newxk=xk + α p;
NewDelk = Df[Newxk];
{Newxk, NewDelk}
]

counter=0;
counterMax=6;
Tol=1.0 (10^(-8));


xk = {1.8,2.0};
Delfk=Df[xk];
While[
And[Norm[Delfk]> Tol,counter++<counterMax],
{xk,Delfk} = NewtonStep[xk,Delfk,{Df, DDf}];
Print["counter=",counter, " xk=", xk, " ||Delfk||=", Norm[ Delfk]]
]