Say I have a non-regular dice defined by probabilities in a list that add up to one, e.g [0.1, 0.3, 0.4, 0.2]
. I can use the following code to simulate rolling that dice n
times:
JavaScript
x
9
1
import random
2
from collections import Counter
3
def roll(dist, n):
4
sides = [i + 1 for i in range(len(dist))]
5
draws = random.choices(population=sides, weights=dist, k=n)
6
return Counter(draws)
7
8
print(roll([0.1, 0.3, 0.4, 0.2], 10000000))
9
Counter({3: 4000343, 2: 2998523, 4: 2000309, 1: 1000825})
However, for large n
, the code gets quite slow, as choices
iterates n
times.
Is there an algorithm which can simulate the dice rolls for any n
in constant time?
Advertisement
Answer
Numpy has this built in as numpy.random.Generator.multinomial:
JavaScript
1
9
1
import numpy as np
2
from collections import Counter
3
4
5
def roll(dist, n):
6
rng = np.random.default_rng()
7
results = rng.multinomial(n, dist)
8
return Counter(enumerate(results, start=1))
9