1
$\begingroup$

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;
grad = Grad[f[x, y], {x, y}];
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?

$\endgroup$
  • 3
    $\begingroup$ Could you upload your code, and not image? $\endgroup$ – Alex Trounev Apr 25 at 23:05
  • 4
    $\begingroup$ 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. $\endgroup$ – J. M.'s technical difficulties Apr 25 at 23:05
  • 1
    $\begingroup$ try adding a ";" after the While[] loop and see if this helps. As others said, hard to use code posted as image. $\endgroup$ – Nasser Apr 26 at 1:52
1
$\begingroup$

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;
grad = Grad[f[x, y], {x, y}];
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]]
 ]
| improve this answer | |
$\endgroup$
  • $\begingroup$ 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. $\endgroup$ – Nelson Amorim Apr 26 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.