This is my first question on Mathematica StackExchange, and I am fairly new to the Mathematica language.
This code aims to evaluate the root of f[x] == 0 between x-values a and b for any given f, and for a specified tolerance tol.
The code gives a Set::setraw error Set::setraw: Cannot assign to raw object 2., and the stack trace indicates that the error lies in the Do loop part.
What is causing the error, and how can I rectify it?
bisect[f_, a_, b_, tol_] :=
Module[{n, mid, fm, root},
{
n = Ceiling[Log[2*((b - a)/tol)]]; (* number of iterations *)
Do[
mid = N[(a + b)/2];
fm = N[f[x] /. x -> mid];
If[fm < 0, a = N[mid], b = N[mid]],
{j, 1, n}];
root = N[(a + b)/2]
Print["Root to f[x] = 0 is ", root];
}];
(* calling program *)
f[x_] := x^2 - 0.9 Cos[x];
a = 0;
b = 2;
tol = 0.0001;
solution = bisect[f, a, b, tol]