0

I'm new to Wolfram Language; I'm trying to get used to it by writing a bunch of code and programs, being one of them the algorithm for the bisection method.

When I write the algorithm outside of a Module, it works:

f[x_] := Sin[x] - 2^x + Log[10, x] + 5
a = 1.0;
b = 3.0;
e = 10^-8;
nmax = 100;

fa = f[a]; fb = f[b]; If[fa fb > 0, Print["Error. Signos Iguales."]; Exit[]] error = b - a; For[n = 1, n <= nmax, n++, error = error/2; c = error + a; fc = f[c]; If[Abs[error] < e, Print["Convergencia"]; Break[]]; If[fa fc < 0, b = c; fb = fc, a = c; fa = fc]; ] Print[c] Plot[f[x], {x, a, b}]

enter image description here

However, I want to properly write the program by writing it inside a Module:

f[x_] := Sin[x] - 2^x + Log[10, x] + 5

biseccion[a_,b_,e_,nmax_]:=Module[{fa,fb,error,n,c,fc}, fa = f[a]; fb = f[b]; If[fa fb > 0, Print["Error. Signos Iguales."]; Exit[]]; error = b - a; For[n = 1, n <= nmax, n++, error = error/2; c = error + a; fc = f[c]; If[Abs[error] < e, Print["Convergencia"]; Break[]]; If[fa fc < 0, b = c; fb = fc, a = c; fa = fc]; ]; Print[c]; Plot[f[x], {x, a, b}] ]

And, when I do so, I get the following error:

enter image description here

I'm sure the solution is very simple, and that this is just a newbie question.. but i have been wrapping my head around this for hours and can not solve it.

Also, now that I'm here, do you know wether it is possible to pass the f[x] as an argument to biseccion instead of just writing it before declaring the module?

*The variable named as $e$ in the aforewritten codes is actually named as $\epsilon$ in the code I wrote in Mathematica.

1 Answers1

2

As defined, a is the name of an argument pattern, not a mutable symbol. By invoking the function as bissecion[1.0... you're defining it to be 1.0. Thus, a=c is rewritten as 1.0=c, which is nonsensical.

Good practice is to list each mutable symbol in your Module definition, and initialize them to arguments as necessary.

John Doty
  • 13,712
  • 1
  • 22
  • 42