mardi 27 avril 2021

More efficient way to formulate if/elif statement based on outcome of np.random.random?

I am attempting to speed up my code which has a long if/elif statement of the following form:

random = np.random.random()
tot = a + b + c + d

if random < a/tot:
   var1 += 1
elif a/tot < random < (a+b)/tot:
   var1 -= 1
elif (a+b)/tot < random < (a+b+c)/tot:
   var2 += 1
elif (a+b+c)/tot < random < tot:
   var2 -= 1

I have tried to figure out a way to do this with a dictionary but I can't figure out how I would index into it. The code works as is, however I am trying to speed up this section of the code which takes a large chunk of the runtime. Is there any other way to do this?




Aucun commentaire:

Enregistrer un commentaire