jeudi 18 août 2016

Fastest way to generate multiple random numbers in a function in Python 2.7/Numpy

I have a function that can use only the standard library of Python2.7 and Numpy.

The body of the function contains lots of call to random.randint() and random.random()

if random.random() < svRate:
    do_stuff

if random.random() < svRate:
    do_stuff

if random.random() < svRate:    
    do_stuff

if random.random() < svRate:    
    do_stuff

if random.random() < svRate:    
    do_stuff

if random.random() < svRate:
    do_stuff

if random.randint(0,5) < pRate:
    do_stuff

if random.randint(0,10) < pRate:
    do_stuff

if random.randint(10,100) < pRate:
    do_stuff

It's lots of boilerplate code and definitely not efficient since all that calls. What is the best way to deal with it? The only solution I could come up with is to generate a list of random numbers in advance and pop() them when I need. Is this the best I can do? Would it actually speed up the code?




Aucun commentaire:

Enregistrer un commentaire