# While loop problem

I have a simple code for bisection method that isn't working correctly. Can someone please tell me what is wrong.

 f[x_] := x*Log[x] + x^2;
Plot[f[x], {x, 0, 1}]
i = 1;
Subscript[a, i] = 0.4;
Subscript[b, i] = 0.6;
Subscript[error, i] = Abs[f[Subscript[x, i]]];
Subscript[error, i] = 1;
While[
Subscript[error, i] >= 0.0001,
Subscript[x, i] = (Subscript[a, i] + Subscript[b, i])/2;
If[
N@f[Subscript[x, i]] > 0,
Subscript[a, i + 1] == Subscript[a, i] &&
Subscript[b, i + 1] ==  Subscript[x, i],
Subscript[a, i + 1] == Subscript[x, i] &&
Subscript[b, i + 1] == Subscript[b, i]
]
Print["iteration ", i , ", output", ": ", Subscript[x, i], ", ",
Subscript[a, i], ", ", Subscript[b, i]]
i++
]

• Avoid the subscripts, except for pretty-printing purposes. It just makes debugging harder to do. Apr 1, 2018 at 17:19

Equal (a.k.a. ==) is a logical operation. You have to use Set (a.k.a. =) in order to assign values to variables. Moreover, And (a.k.a. &&) is a logical operation; use a semicolon ; instead. This is the cleaned code, incoporating J.M.'s remark on Subscript.

f[x_] := x Log[x] + x^2;
Plot[f[x], {x, 0, 1}]
i = 1;
imax = 100;
ClearAll[a, b, x, error, c];
a[i] = 0.4;
b[i] = 0.6;
x[i] = b[i];
error[i] = Abs[f[x[i]]];
While[error[i] >= 0.0001 && i < imax,
x[i + 1] = (a[i] + b[i])/2.;
c = f[x[i + 1]];
If[c > 0.,
a[i + 1] = a[i]; b[i + 1] = x[i + 1],
a[i + 1] = x[i + 1]; b[i + 1] = b[i]
];
error[i + 1] = Abs[c];
Print["iteration ", i, ", output", ": ", x[i], ", ", a[i], ", ", b[i]];
i++;
]


Remark

Performancewise, it would be better to forget old iterates and simply reuse the variables, a, b, x, and error:

i = 1;
imax = 100;
ClearAll[a, b, x, error];
a = 0.4;
b = 0.6;
x = b;
error = Abs[f[x]];
While[error >= 0.0001 && i < imax,
x = (a + b)/2.;
c = f[x];
If[c > 0.,
a = a; b = x,
a = x; b = b
];
error = Abs[c];
i++;
]

• Thank you very much :) Apr 1, 2018 at 18:20
• You're welcome! Apr 1, 2018 at 18:21