mardi 20 septembre 2022

Is there a way to vectorize this loop?

I'm trying to simulate the results of two different dice. One die is fair (i.e. the probability of each number is 1/6), but the other isn't.

I have a numpy array with 0's and 1's saying which die is used every time, 0 being the fair one and 1 the other. I'd like to compute another numpy array with the results. In order to do this task, I have used the following code:

def dice_simulator(dices : np.array) -> np.array:
  n = len(dices)
  results = np.zeros(n)
  i = 0
  for dice in np.nditer(dices):
    if dice:
      results[i] = rnd.choice(6, p = [1/12, 1/12, 1/12, 1/4, 1/4, 1/4]) + 1
    else:
      results[i] = rnd.choice(6) + 1
    i += 1
  return results

This takes a lot of time compared to the rest of the program, and think it is because I'm iterating over a numpy array instead of using vectorization of operations. Can anyone help me with that?




Aucun commentaire:

Enregistrer un commentaire