Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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?

share|improve this question
    
what is the definition of f[x,y] ? –  lalmei Oct 9 '13 at 16:15
    
@lalmei I added f[x,y] and the initializations, please take a look again. –  user271827 Oct 9 '13 at 16:18

1 Answer 1

up vote 4 down vote accepted

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[]];]
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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