Vectorized sampling of multiple binomial random variables

大城市里の小女人 提交于 2021-01-28 23:36:06

问题


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?


回答1:


Here you go,

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? Yes
results = np.empty(N_random_variables)
results = np.random.binomial(n_vals, p_vals)


来源:https://stackoverflow.com/questions/31062092/vectorized-sampling-of-multiple-binomial-random-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!