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
  • 3
    $\begingroup$ Could you upload your code, and not image? $\endgroup$ Apr 25, 2020 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$ Apr 25, 2020 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, 2020 at 1:52

1 Answer 1

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]]
 ]
$\endgroup$
1
  • $\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$ Apr 26, 2020 at 19:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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