Clarity vs. code reuse/generality

Paul Rubin http
Fri Jul 3 12:33:35 EDT 2009

kj < at> writes:
>     sense = cmp(func(hi), func(lo))
>     if sense == 0:
>         return None
>     target_plus = sense * target + epsilon
>     target_minus = sense * target - epsilon
>     ...

The code looks confusing to me and in some sense incorrect.  Suppose
func(hi)==func(lo)==target.  In this case the solver gives up
and returns None even though it already has found a root.

Also, the stuff with the sense parameter, and target_minus and
target_plus looks messy.  I do like to use cmp.  I'd just write
something like (untested):

 def _binary_search(lo, hi, func, target, epsilon):
     y_hi, y_lo = func(hi), func(lo)
     while True:
         x_new = (lo + hi) * 0.5
         y_new = func(x_new)
         if abs(y_new - target) < epsilon: 
            return x_new
         elif cmp(y_new, target) == cmp(y_hi, target):
            hi = x_new
            lo = x_new
         if lo == hi:
            return None 

This uses an extra couple function calls in that trivial case, of

More information about the Python-list mailing list