# How to make this bisection code work for different equations?

I am very new to Mathematica. I have this code of Bisection Method for finding a root of a polynomial.

Bisection[a0_, b0_, e0_, n_] := Module[{},
a = N[a0];
b = N[b0];
e = N[e0];
i = 0;
f[x_] := x^2 - x - 12;
Output = {{i, a, b, }};
While[i < n,
c = (a + b)/2;
Output = Append[Output, {i + 1, a, b, c}];
If[Sign[f[b]] == Sign[f[c]], b = c, a = c];
If[(b - a)/2 < e, Print["Condition Exists at ", i + 1, " . "];
Break[] ];
i = i + 1;
];
Print[NumberForm[TableForm[Output,
TableHeadings -> {None, {"i", "a{i}", "b{i}", "c{i}"}}], 16]];
Print["Root p = ", NumberForm[c, 16] ];
Print[f[x]] ;
Plot[f[x], {x, -4, 5}]
]

Bisection[-4, 2, 10^-5, 10]

It works fine for an example then if I want to use it for other example I have to change the code or copy it for other examples. How can I modify this code so that it takes an equation as an input and I can just used the command (or something like this)

Bisection[x^2 - x - 12,-4, 2, 10^-5, 10]
Bisection[x^3 + x,-4, 2, 10^-5, 10]

which should work for any equation.

• Remove the f[x_]... line and pass f in as an argument like Bisection[f_, a0_, b0_, e0_, n_] := Module[{}, ... . You can then define poly = Function[{x}, x^3 -x^2 + .... ] or whatever outside and pass in poly. Apr 30, 2023 at 7:19
• I tried that, doesn’t work. Apr 30, 2023 at 7:24
• 'doesn't work' how? Apr 30, 2023 at 7:26
• It should work. Sounds like you didn't define poly as a function poly[x_]:= or using Function as a I described or you have not cleared the old definition. Apr 30, 2023 at 7:30
• You don't need the extra function call if you're going to define poly that way. poly[u_]:=u^3-u-12 is enough. Apr 30, 2023 at 9:31

Here is you changed code that should work:

poly[x_] = x^2 - x - 12;
Bisection[f_, a0_, b0_, e0_, n_] := Module[{}, a = N[a0];
b = N[b0];
e = N[e0];
i = 0;
Output = {{i, a, b}};
While[i < n, c = (a + b)/2;
Output = Append[Output, {i + 1, a, b, c}];
If[Sign[f[b]] == Sign[f[c]], b = c, a = c];
If[(b - a)/2 < e, Print["Condition Exists at ", i + 1, " . "];
Break[]];
i = i + 1;];
Print[
NumberForm[
TableForm[Output,
TableHeadings -> {None, {"i", "a{i}", "b{i}", "c{i}"}}], 16]];
Print["Root p = ", NumberForm[c, 16]];
Print[f[x]];
Plot[f[x], {x, -4, 5}]];

Now, e.g. for your first polynomial:

Bisection[poly, -4, 2, 10^-5, 10]

• Thanks its working now. Apr 30, 2023 at 8:21
• is there anything else that can be changed in the code so that it works better or faster? Apr 30, 2023 at 8:21
• You could replace "Append" by "Reap" and "Sow" Apr 30, 2023 at 9:43