Pseudocode

INPUT: function $f$ and an interval $[a, b]$ such that $f(a)f(b) < 0$.
PARAMS: tolerance $\epsilon$.

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!

Pseudocode

INPUT: function $f$ and an interval $[a, b]$ such that $f(a)f(b) < 0$.
PARAMS: tolerance $\epsilon$.

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.

Pseudocode

INPUT: function $f$ and an interval $[a, b]$ such that $f(a)f(b) < 0$.
PARAMS: tolerance $\epsilon$.

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.

OK, but what's the catch?

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.

Consider the function $f(x) = x^2$ with root $p = 0$.
Altough $f(0) = 0$, there is no interval in which $f$ changes sign: $f(x) \geq 0$ for all $x$!

Any other shortcomings?

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.

So what can we do?

The bisection method simply fails to approximate roots of even multiplicity. Unfortunately, there's nothing we can do about it.

In the next couple of lectures we will define the notion of multiplicity and we will discuss a different class of root finding methods.
Congratulations! You have reached the end of this lecture.