# 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 = 0;
y = 0;
ϵ = 10.^-8;
k = 1;
J = grad /. {x -> x, y -> y};
S = -J;
While[Norm[S] > ϵ,
g = f[x, y] /. {x -> x[k] + λ*S[],
y -> y[k] + λ*S[]};
novo = {x[k], y[k]};
eqlamb = D[g, λ];
lamb = Solve[eqlamb == 0, λ][[1, 1, 2]];
x[k + 1] = novo + lamb*S[];
y[k + 1] = novo + lamb*S[];
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? – Alex Trounev Apr 25 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. – J. M.'s technical difficulties Apr 25 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. – Nasser Apr 26 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 = 0;
y = 0;
ϵ = 10.^-8;
k = 1;
J = grad /. {x -> x, y -> y};
S = -J;
While[Norm[S] > ϵ,
g = f[x, y] /. {x -> x[k] + λ*S[], y -> y[k] + λ*S[]};
novo = {x[k], y[k]};
eqlamb = D[g, λ];
lamb = Solve[eqlamb == 0, λ][[1, 1, 2]];
x[k + 1] = novo[] + lamb*S[];
y[k + 1] = novo[] + lamb*S[];
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. – Nelson Amorim Apr 26 at 19:28