What is the most efficient way to get a multinomial distribution (say for n=1 trial) in cython?
For example, I have three probabilities p0=0.1, p1=0.2, p2=0.7 (which sum to 1) and want to have x to be 0, 1, 2 with probability p0, p1, p2 respectively.
I tried
cimport numpy as np
import numpy as np
# the data types
cdef np.ndarray[double, ndim=1] p
cdef int x
rng = np.random.default_rng() # the random number generator from numpy
p = np.array([0.1,0.2,0.7]) # the probabilities
x = <int>(rng.multinomial(1, p, size=1).argmax(axis=-1)[0])
But this is very slow, since it has to use a lot of python code. Is there a faster way, which used a good random number generator?
(Side note: I use multinomial
instead of choice
from numpy since it has the issue of p only almost summing up to 1 due to rounding errors fixed.)