pdpi <pdpinhe...@gmail.com> writes: > while abs(func(guess) - target) > epsilon: > guess = (lo + hi) / 2. > if sense * func(guess) > sense * target: > hi = guess > elif sense * func(guess) < sense * target: > lo = guess > elif lo == hi: > return None > return guess
That is completely confusing. I get the, er, impression that "sense" is supposed to change during the loop, and it takes much head scratching to tell whether what you have there is right or not. Also, it calls func 3 times on each loop, which could be extremely slow. You don't know what func does, so eliminating 2/3 of the calls to it is not a micro-optimization--it could be a major time saving. Yet another version: def _binary_search(x0, x1, func, target, epsilon): y0,y1 = func(x0), func(x1) while abs(y1 - target) > epsilon: if x0 == x1 or cmp(y0,target) == cmp(y1,target): return None xn = (x0 + x1) / 2. yn = func(xn) if cmp(yn,target) == cmp(y0,target): x0,y0 = xn,yn else: x1,y1 = xn,yn return x1 -- http://mail.python.org/mailman/listinfo/python-list