Created
February 18, 2015 18:01
-
-
Save NapalmHorn/d0caf329cf916371daf9 to your computer and use it in GitHub Desktop.
bi_funct_search
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 bi_funct_search(f, x, low=0, high=None): | |
"""a text book binary search against a function | |
f is a strictly increasing function | |
x is a number in (low, high) and the domain of f | |
low is lower bound | |
high is upperbound (usually should not be omitted) | |
returns z such that f(z) = x or None if not found""" | |
if high is None: | |
high = x ** 2 | |
while low < high: | |
mid = (low + high) // 2 | |
midval = f(mid) | |
if midval < x: | |
low = mid + 1 | |
elif midval > x: | |
high = mid | |
else: | |
return mid | |
return None # to show x was not found |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment