0
$\begingroup$

I am having trouble with the while loop not breaking,

f[x_, y_] = 2 x^2 + 5 y^2;
dfx[x_, y_] = D[f[x, y], x];
dfy[x_, y_] = D[f[x, y], y];
a = 10.; 
b = 10.; 
aold = 0; 
bold = 0; 
count=0;

While[ Abs[f[a, b] - f[aold, bold]] > 10^-5,
       aold = a; bold = b; 
       α = dfx[a, b]; β = dfy[a, b]; 
       l[t_] = {a, b} + t*{α, β};
       h[t_] = f[l[t][[1]], l[t][[2]]];
       dh[t_] = D[h[t], t];
       tnew = t /. Solve[dh[t] == 0, t];
       a = a + tnew*α;
       b = b + tnew*β;
       count++;
       If[count == 10, Break[]];
   ]

When I print the output, value of Abs[f[a, b] - f[aold, bold]] is way smaller than $10^{-5}$, the condition should be met around 5 loops. Can you see what is wrong with the code?

$\endgroup$
2
  • $\begingroup$ what is the definition of f[x,y] ? $\endgroup$
    – lalmei
    Oct 9, 2013 at 16:15
  • $\begingroup$ @lalmei I added f[x,y] and the initializations, please take a look again. $\endgroup$
    – user271827
    Oct 9, 2013 at 16:18

1 Answer 1

4
$\begingroup$

The problem is that the tnew defined as you have it is a list. See this page for help on this matter. So when you add a, initially a constant, to tnew it becomes a list also. Then when you try to test the condition, you are asking whether a list is greater than a constant and Mahtematica won't evaluate that.

Try this:

f[x_, y_] = 2 x^2 + 5 y^2;
dfx[x_, y_] = D[f[x, y], x];
dfy[x_, y_] = D[f[x, y], y];
a = 10.; b = 10.; aold = 0; bold = 0; count = 0;
While[ Abs[f[a, b] - f[aold, bold]] > 10^-5, aold = a; bold = b;
       α = dfx[a, b];
       β = dfy[a, b];
       l[t_] = {a, b} + t*{ α, β};
       h[t_] = f[l[t][[1]], l[t][[2]]];
       dh[t_] = D[h[t], t];
       tnew = t /. Solve[dh[t] == 0, t][[1]];
       a = a + tnew*α;
       b = b + tnew*β;
       count++;
       If[ count == 10, Break[]];]
$\endgroup$

Your Answer

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

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