Created
August 29, 2022 06:13
-
-
Save theabbie/5f6cf5ff0de8bc1b364e6bc0fe554087 to your computer and use it in GitHub Desktop.
Inverse of a function using binary search
This file contains hidden or 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 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