Created
February 4, 2015 16:54
-
-
Save eddotman/33fc149c9ff6c1da6398 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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