On Jul 7, 7:06 pm, Paul Rubin <http://phr...@nospam.invalid> wrote: > pdpi <pdpinhe...@gmail.com> writes: > > Personally, I think the code is an unreadable mess, but that's mostly > > because of all the micro optimizations, not the generality of it. > > Here's my unoptimized, but still equally generic, version: > > That version doesn't use "sense" inside the binary search, i.e. it > relies on the function being monotonically increasing.
You're right, make that: def _binary_search(lo, hi, func, target, epsilon): sense = cmp(func(hi), func(lo)) if sense == 0: return None guess = (lo + hi) / 2. while abs(func(guess) - target) > epsilon: guess = (lo + hi) / 2. if sense * func(guess) > target: hi = guess elif sense * func(guess) < target: lo = guess elif lo == hi: return None return guess Seems I had a serious brain cramp while posting that... -- http://mail.python.org/mailman/listinfo/python-list