Reputation: 1855
numpy.random.uniform
supports array arguments, but numpy.random.randint
does not:
import numpy as np
two_random_uniforms = np.random.uniform([0, 1], [3, 4])
this_raises_exception = np.random.randint([0, 1], [3, 4])
The behavior I want from the second line of code is equivalent to:
result = []
for lown, highn in zip([0, 1], [3, 4]):
result.append(np.random.randint(lown, highn))
Is there a way to accomplish the random integer generation with variable max/min without writing a Python loop? The above workaround will be unacceptably slow for the large arrays that my application requires. I can write the loop in Cython, but I'd rather use NumPy if possible.
Upvotes: 3
Views: 1430
Reputation: 131550
One simple thing you could do is just generate floats and round them.
def my_randint(low, high):
return np.floor(np.random.uniform(low, high))
It's possible this procedure might tweak the resulting distribution a bit, to make some integers ever so slightly more likely than others, but unless you are working with cryptography or some other sensitive application, it probably won't matter.
Upvotes: 2