Skip to content

Instantly share code, notes, and snippets.

@NapalmHorn
Created February 18, 2015 18:01
Show Gist options
  • Save NapalmHorn/d0caf329cf916371daf9 to your computer and use it in GitHub Desktop.
Save NapalmHorn/d0caf329cf916371daf9 to your computer and use it in GitHub Desktop.
bi_funct_search
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