Generic Bisection Solver

Given some function f and a goal value, this program uses bisection to seek a value x such that f(x) = goal.

For example, suppose you want √(101). Our goal is really to find some value x² = 101. There is some "right way" to calculate this, but suppose you do not know it. How can we estimate the value? With bisection! All we need is to search for x values where x² ≈ 101 until we cannot improve our estimate any further.

These can be kind of confusing to think about. It helps me to to say something along the lines of "when I look at x, I know that x = √(101) because x² = 101." Really, we are looking for an inverse function f(f⁻¹(x)) = x, but these are sometimes difficult or impossible to find.

The idea is that you start with a low estimate (lo) and a high estimate (hi). Compute mid = lo + (hi-lo)/2 and compare f(mid) to the goal. If goal < f(mid) then we branch left, searching between lo ≤ x ≤ mid, otherwise we branch right and search between mid ≤ x ≤ hi. Branching is reversed if the slope is negative. If the interval contains an inflection point (slope transitions from positive to negative or negative to positive) then this program is not guaranteed to produce a correct solution.