Skip to content

Instantly share code, notes, and snippets.

@eddotman
Created February 4, 2015 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eddotman/33fc149c9ff6c1da6398 to your computer and use it in GitHub Desktop.
Save eddotman/33fc149c9ff6c1da6398 to your computer and use it in GitHub Desktop.
def bin_search(f, y, lo, hi, tol, nmax):
mid = (hi + lo)/2.
if f(lo) < y < f(hi) or f(lo) > y > f(hi):
for i in range(nmax):
fmid = f(mid)
if abs(fmid - y) <= tol: break
if (fmid < y and f(lo) < f(hi)) or (fmid > y and f(lo)>f(hi)):
#going right
lo = mid
else:
#going left
hi = mid
mid = (hi+lo)/2.
return fmid
else:
raise ValueError("end points don't bracket the target")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment