# While loop not breaking when condition is met

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][], l[t][]];
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?

• 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

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][], l[t][]];
dh[t_] = D[h[t], t];
tnew = t /. Solve[dh[t] == 0, t][];
a = a + tnew*α;
b = b + tnew*β;
count++;
If[ count == 10, Break[]];]