First I plot the function and then I try to find a domain such that I can see the curve cut through the x-axis. I do this via trial and error
f[x_] := x^6 - x - 1;
Plot[f[x], {x, -1, 1}]
this is my code. How can I improve it?
a = -1;
b = 0; (*define the initial domain [a,b] *)
(*tolerence*)
epsilon = 0.001;
(*initialistation*)
count = 0;
countvalve = 100;
c = 0.5*(a + b);
While[Abs[f[c]] > epsilon,
count = count + 1;
c = 0.5*(a + b);
If[f[c]*f[a] < 0, b = c, a = c];
If[count > countvalve, Break[]];
Print[{count, c, f[c], epsilon}];];
Print["While loop exited"];
Print[{count, c, f[c], epsilon}];
Plot[f[x], {x, c - 0.1, c + 0.1}]
this is the output
{1,-0.5,-0.484375,0.001} {2,-0.75,-0.0720215,0.001} {3,-0.875,0.323795,0.001} {4,-0.8125,0.1002,0.001} {5,-0.78125,0.00862368,0.001} {6,-0.765625,-0.0329578,0.001} {7,-0.773438,-0.0124947,0.001} {8,-0.777344,-0.00201909,0.001} {9,-0.779297,0.00328119,0.001} {10,-0.77832,0.000625803,0.001} While loop exited {10,-0.77832,0.000625803,0.001}
Suppose the function contains two roots. how do I find the other one?
but this is the real question,
How do I write a code to implement bisection method so that, given any continuous function $f(x)$, the code can
Count the number of roots in a domain [a,b]
Evaluate each of these roots one by one in sequence.
where epsilon = 0.001
these are sample functions.
f[x] = Exp[x] - x - 2; (* for all x *)
f[x] = x^3 + (2*x)^2 - 3*x - 1; (*for all x *)
f[x] = (1/x)Sin[x]; (* for -3 π <= x <= 3 π *)
f[x] = Tan[π*x] -x - 6; (* for -3 π <= x <= 3 π *)
The code should be able to find all the roots in all the functions automatically and without manual intervention.




FindRoot[f[x], {x, 0.1}]. Then scan through many different starting values. $\endgroup$NSolve[f[x] == 0 && a <= x <= b, x]? -- Are you required to use the bisection method? You'll need another algorithm to isolate the roots. I take it this is a homework assignment, because the only other reason I can think of trying this way is for fun. $\endgroup$