jeudi 25 juin 2015

Vectorized sampling of multiple binomial random variables

I would like to sample a few hundred binomially distributed random variables, each with a different n and p (using the argument names as defined in the numpy.random.binomial docs). I'll be doing this repeatedly, so I'd like to vectorize the code if possible. Here's an example:

import numpy as np

# Made up parameters
N_random_variables = 500
n_vals = np.random.random_integers(100, 200, N_random_variables)
p_vals = np.random.random_sample(N_random_variables)

# Can this portion be vectorized?
results = np.empty(N_random_variables)
for i in xrange(N_random_variables):
    results[i] = np.random.binomial(n_vals[i], p_vals[i])

In the special case that n and p are the same for each random variable, I can do:

import numpy as np

# Made up parameters
N_random_variables = 500
n_val = 150
p_val = 0.5

# Vectorized code
results = np.random.binomial(n_val, p_val, N_random_variables)

Can this be generalized to the case when n and p take different values for each random variable?




Aucun commentaire:

Enregistrer un commentaire