0
$\begingroup$

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++
 ]
$\endgroup$
1
  • 2
    $\begingroup$ Avoid the subscripts, except for pretty-printing purposes. It just makes debugging harder to do. $\endgroup$ Apr 1, 2018 at 17:19

1 Answer 1

2
$\begingroup$

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++;
 ]
$\endgroup$
2
  • $\begingroup$ Thank you very much :) $\endgroup$
    – user57225
    Apr 1, 2018 at 18:20
  • $\begingroup$ You're welcome! $\endgroup$ Apr 1, 2018 at 18:21

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.