Created
March 31, 2018 11:56
-
-
Save erikseulean/8bab929b6745707d4c1551002f9e03ea to your computer and use it in GitHub Desktop.
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
| ''' | |
| given a function and a value y, find the bext x for which |f(x) - y| is minimal | |
| ''' | |
| def get_boundaries(func, y): | |
| # x * x > max_value #overflow | |
| # sqrt(max_value) < x # next x will be overflow | |
| # in python this is not an issue but it could be in some other languages | |
| x = 1 | |
| prev = 0 | |
| while func(x) < y | |
| prev = x | |
| x = x * x | |
| return prev, x | |
| def get_best_value(func, y): | |
| left, right = get_boundaries(func, y) | |
| sol = left | |
| while left <= right: | |
| mid = left + (right - left) / 2 | |
| if func(mid) <= y: | |
| left = mid + 1 | |
| else func(mid) > y: | |
| right = mid - 1 | |
| if math.abs(func(mid) - y) < math.abs(func(sol) - y): | |
| sol = mid | |
| return sol |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment