Python: fastest way to check in which interval number is in
Suppose I have split the interval [0, 1] into a series of smaller intervals [0, 0.2), [0.2, 0.4), [0.4, 0.9), [0.9, 1.0]. Now I sample a value r in [0, 1]. What is the fastest way I can check in which interval this belongs to using Python / Numpy / Pytorch?
The obvious way is this:
r = np.random.rand()
if 0 &lt;= r &lt; 0.2:
    pass # do something
elif 0.2 &lt;= r &lt; 0.4:
    pass # do something else
elif 0.4 &lt;= r &lt; 0.9:
    pass # do yet something else again
elif 0.9 &lt;= r &lt;= 1.0:
    pass # do some other thing




You'll want to first transform your list of intervals into a list of boundaries, so instead of many intervals [0, 0.2), [0.2, 0.4), [0.4, 0.9), [0.9, 1.0], you just define:
boundaries = [0, 0.2, 0.4, 0.9, 1.0]  # values must be sorted!!

Then you can perform a binary search over all of them, to see in which segment a value belongs:
index = bisect.bisect_right(boundaries, value)

index will be the index of the upper bound, so to get the range, you'd to:
range_low = boundaries[index - 1] if index &gt; 0 else None
range_high = boundaries[index] if index &lt; len(boundaries) else None

This will also take care of handling values which are not in any of the intervals. The binary search will be done in log(N) compares, which is the theoretical best thing you can do for arbitrary intervals.
