My objective is to build a function using modules that runs the bisection method. I have a working bisection method but when I try to implement it as a module I keep getting this error and I can’t figure out why.
F[z_]:=3 + z + z^2 * Cos[z] bisectionMethod[f_, a_, b_, n_] := Module[ {}, For[i = 0, i < n, i++, Print[StringForm["Loop #: ``", i + 1]]; c = (a + b)/2; y = f[c]; If[y < 0, a = c]; If[y > 0, b = c]; Print[StringForm["a = ``", N[a]]]; Print[StringForm["b = ``", N[b]]]; c = (a + b)/2; Print[StringForm["c = ``", N[c]]]; Print[N[f[c]]]; ] ] bisectionMethod[F, -4 , 2 , 10]
After being run
Loop #: 1 Set::setraw: Cannot assign to raw object 2. a = -4. b = 2.` c = -1. 2.5403 Loop #: 2 Set::setraw: Cannot assign to raw object 2. a = -4. b = 2.` c = -1. 2.5403
The issue appears to be specifically variable b but I have no idea how b is any different from the others and how to tackle this.
I did a little bit of experimentation and it seems like the line If[y > 0, b = c];
is problematic