1 function [root,iterations] = bisect(f, a, b, epsilon)
2 ## Find a root of the function `f` on the closed interval [a,b].
4 ## It is assumed that there are an odd number of roots within [a,b].
5 ## The intermediate value theorem is used to determine whether or not
6 ## there is a root on a given interval. So, for example, cos(-2) and
7 ## cos(2) are both less than zero; the I.V.T. would not conclude that
8 ## cos(x) has a root on -2<=x<=2.
10 ## If `f` has more than one root on [a,b], the smallest root will be
11 ## returned. This is an implementation detail.
16 ## * ``f`` - The function whose root we seek.
18 ## * ``a`` - The "left" endpoint of the interval in which we search.
20 ## * ``b`` - The "right" endpoint of the interval in which we search.
22 ## * ``epsilon`` - How close we should be to the actual root before we
23 ## halt the search and return the current approximation.
27 ## * ``root`` - The root that we found.
29 ## * ``iterations`` - The number of bisections that we performed
33 ## Store these so we don't have to recompute them.
37 ## We first check for roots at a,b before bothering to bisect the
51 ## Bisect the interval.
55 ## If we're within the prescribed tolerance, we're done.
61 if (has_root(fa,f(c)))
62 [root,subiterations] = bisect(f,a,c,epsilon);
63 iterations = iterations + subiterations;
65 [root,subiterations] = bisect(f,c,b,epsilon);
66 iterations = iterations + subiterations;