Drawing random numbers with a draw in some predetermined interval, `numpy.random.choice ()`

I would like to use numpy.random.choice(), but make sure that the draws are spaced at least a certain “interval”:

As a concrete example,

import numpy as np
np.random.seed(123)
interval = 5
foo = np.random.choice(np.arange(1,50), 5)  ## 5 random draws between array([ 1,  2, ..., 50])
print(foo)
## array([46,  3, 29, 35, 39])

I would prefer that they be spaced at least by interval+1, that is, 5 + 1 = 6. In the above example, this condition is not fulfilled: there must be another random draw, since 35 and 39 are divided by 4, which is less than 6.

The array array([46, 3, 29, 15, 39])will be in order, since all the drawings will be located at a distance of at least 6.

numpy.random.choice(array, size) size array. , "" numpy? if/while, , numpy.

+4
2

, :

def spaced_choice(low, high, delta, n_samples):
    draw = np.random.choice(high-low-(n_samples-1)*delta, n_samples, replace=False)
    idx = np.argsort(draw)
    draw[idx] += np.arange(low, low + delta*n_samples, delta)
    return draw

:

spaced_choice(4, 20, 3, 4)
# array([ 5,  9, 19, 13])
spaced_choice(1, 50, 5, 5)
# array([30,  8,  1, 15, 43])

, , . 10, accpet/reject . insert-the-spaces-after .

, :

low, high, delta, size = 1, 100, 5, 5
add_spaces            0.04245870 ms
redraw                0.11335560 ms
low, high, delta, size = 1, 20, 1, 10
add_spaces            0.03201030 ms
redraw            27881.01527220 ms

:

import numpy as np

import types
from timeit import timeit

def f_add_spaces(low, high, delta, n_samples):
    draw = np.random.choice(high-low-(n_samples-1)*delta, n_samples, replace=False)
    idx = np.argsort(draw)
    draw[idx] += np.arange(low, low + delta*n_samples, delta)
    return draw

def f_redraw(low, high, delta, n_samples):
    foo = np.random.choice(np.arange(low, high), n_samples)
    while any(x <= delta for x in np.diff(np.sort(foo))):
        foo = np.random.choice(np.arange(low, high), n_samples)
    return foo

for l, h, k, n in [(1, 100, 5, 5), (1, 20, 1, 10)]:
    print(f'low, high, delta, size = {l}, {h}, {k}, {n}')
    for name, func in list(globals().items()):
        if not name.startswith('f_') or not isinstance(func, types.FunctionType):
            continue
        print("{:16s}{:16.8f} ms".format(name[2:], timeit(
                'f(*args)', globals={'f':func, 'args':(l,h,k,n)}, number=10)*100))
+3

, , np.diff, . - , interval, . ..

import numpy as np

interval = 5
foo = np.random.choice(np.arange(1,50),5)
while np.any(np.diff(np.sort(foo)) <= interval):
     foo = np.random.choice(np.arange(1,50),5)
print(foo)

, numpy, , , interval.

+1

Source: https://habr.com/ru/post/1691264/


All Articles