Last active
January 9, 2016 09:29
-
-
Save eviatarbach/80e0accb7e8bf590ffc4 to your computer and use it in GitHub Desktop.
A Python function that, given a lookup value, will find the index of the closest value in an equally-spaced list of numbers in constant time
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 closest_index_in_range(lower, upper, step, value): | |
''' | |
Find the index of the closest value to `value` in the range | |
[lower, lower + step, ..., upper - step, upper] in constant time. `upper` | |
must be greater than `lower`. If `value` is outside the range, return the | |
corresponding boundary index (0 or the last index). When two values are | |
equally close, the index of the smaller is returned. | |
For example, `closest_index_in_range(-5, 5, 0.5, -4.8)` will return 0, since | |
-4.8 is closest to -5. | |
''' | |
if value >= upper: | |
return int((upper - lower)/step) | |
elif value < lower: | |
return 0 | |
value = value - lower | |
upper = upper - lower | |
lower = 0 | |
index = int(value//step + 1) | |
if step*index - value >= value - step*(index - 1): | |
index -= 1 | |
return index |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment