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.
f[x_]...
line and passf
in as an argument likeBisection[f_, a0_, b0_, e0_, n_] := Module[{}, ...
. You can then definepoly = Function[{x}, x^3 -x^2 + .... ]
or whatever outside and pass in poly. $\endgroup$poly[u_]:=u^3-u-12
is enough. $\endgroup$