Fletcher-Reeves Method

I'm trying to implement the Fletcher-Reeves Method, the code is:

f[x_, y_] := x - y + 2*x^2 + 2*x*y + y^2;
x[1] = 0;
y[1] = 0;
ϵ = 10.^-8;
k = 1;
J = grad /. {x -> x[1], y -> y[1]};
S = -J;
While[Norm[S] > ϵ,
g = f[x, y] /. {x -> x[k] + λ*S[[1]],
y -> y[k] + λ*S[[2]]};
novo = {x[k], y[k]};
eqlamb = D[g, λ];
lamb = Solve[eqlamb == 0, λ][[1, 1, 2]];
x[k + 1] = novo[1] + lamb*S[[1]];
y[k + 1] = novo[2] + lamb*S[[2]];
Jold = grad /. {x -> x[k], y -> y[k]};
k++;
Jnew = grad /. {x -> x[k], y -> y[k]};
S = -Jnew + (Norm[Jnew])^2/(Norm[Jold])^2*S;
Print["The number of iterations = ", k]
Print["x = ", x[k + 1], " ", "y = ", y[k + 1]]]


But, when I run the code, the answer does not appear, any suggestion?

• Could you upload your code, and not image? Apr 25, 2020 at 23:05
• Forcing people to retype all the code will markedly decrease the chances that anyone will be interested in helping you. Instead of attaching a screenshot, select all the code, right-click and select "Copy As > Input Text", and paste the code in your question. Apr 25, 2020 at 23:05
• try adding a ";" after the While[] loop and see if this helps. As others said, hard to use code posted as image. Apr 26, 2020 at 1:52

There were just small misprints, after correcting it seems to work, however, check λ:

f[x_, y_] := x - y + 2*x^2 + 2*x*y + y^2;
x[1] = 0;
y[1] = 0;
ϵ = 10.^-8;
k = 1;
J = grad /. {x -> x[1], y -> y[1]};
S = -J;
While[Norm[S] > ϵ,
g = f[x, y] /. {x -> x[k] + λ*S[[1]], y -> y[k] + λ*S[[2]]};
novo = {x[k], y[k]};
eqlamb = D[g, λ];
lamb = Solve[eqlamb == 0, λ][[1, 1, 2]];
x[k + 1] = novo[[1]] + lamb*S[[1]];
y[k + 1] = novo[[2]] + lamb*S[[2]];
Jold = grad /. {x -> x[k], y -> y[k]};
k++;
Jnew = grad /. {x -> x[k], y -> y[k]};
S = -Jnew + (Norm[Jnew])^2/(Norm[Jold])^2*S;
Print["The number of iterations = ", k];
Print["x = ", x[k], " ", "y = ", y[k]]
]

• Thanks yarchik !, it works, really the output it was x[k] and y[k], and few modifications using part (novo) of the code. My best regards from Brazil. Apr 26, 2020 at 19:28