Skip to content

Instantly share code, notes, and snippets.

@theabbie
Created August 29, 2022 06:13
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 theabbie/5f6cf5ff0de8bc1b364e6bc0fe554087 to your computer and use it in GitHub Desktop.
Save theabbie/5f6cf5ff0de8bc1b364e6bc0fe554087 to your computer and use it in GitHub Desktop.
Inverse of a function using binary search
def inverse(x, f, k = 15):
beg = 0
end = 1
while f(end) < x:
beg += 1
end += 1
while k:
mid = (beg + end) / 2
if f(mid) > x:
end = mid
else:
beg = mid
k -= 1
return beg
lambert = lambda y: y * (2.71828 ** y)
x = 3
res = inverse(x, lambert)
print(f"f({res:.5f}) = {lambert(res):.5f} != {x}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment