Skip to content

Instantly share code, notes, and snippets.

@eddotman
Created February 4, 2015 17:03
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/4db82d7607f886fdb983 to your computer and use it in GitHub Desktop.
Save eddotman/4db82d7607f886fdb983 to your computer and use it in GitHub Desktop.
def bin_search(f, y, lo, hi, tol, nmax):
if f(lo) < y < f(hi) or f(lo) > y > f(hi):
for i in range(nmax):
mid = (hi+lo)/2.
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
return mid
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