for k in 1, ..., maxIter:
p = (a + b) / 2
if (b-a)/2 < eps:
return p
sfp = sgn(f(p))
if sfa * sfp < 0:
b = p
else:
a = p
sfa = sfp
When possible, use a $\texttt{for}$ loop instead of a $\texttt{while}$ loop to ensure your calculation terminates.
You don't want to run up your tab on the server because a tiny bug prevented your stopping condition from triggering!
for k in 1, ..., maxIter:
p = (a + b) / 2
if (b-a)/2 < eps:
return p
sfp = sgn(f(p))
if sfa * sfp < 0:
b = p
else:
a = p
sfa = sfp
Stop when the absolute error is at most $\epsilon$. The error bound is guaranteed by our theorem.
for k in 1, ..., maxIter:
p = (a + b) / 2
if (b-a)/2 < eps:
return p
sfp = sgn(f(p))
if sfa * sfp < 0:
b = p
else:
a = p
sfa = sfp
If the function changes sign on the left half of the interval, we set the left half as our new interval. Otherwise, we choose the right half.
From our convergence theorem results a simple recipe for approximating roots which is guaranted to converge when $f$ and the starting values $a, b$ satisfy $f(a)f(b) < 0$.
The problem is that not every root of every function is cointained in such an interval.
The problem is that not every root of every function is cointained in such an interval.
If $f$ has multiple roots in $[a, b]$, our method will converge to a root of $f$, but a priori we don't know to which one.
The bisection method simply fails to approximate roots of even multiplicity. Unfortunately, there's nothing we can do about it.