I'd like to generate random samples on python, but each with their own standard deviation.
I thought I could use
np.random.normal(0, scale=np.array(standard_deviation), size=(len(np.array(standard_deviation)), number_of_simulations)
However, bumpy seems not to work when I put an array for scale (which is contrary to what I understand from the documentation) and only wants a float as an argument.
My goal is to render an array of size (Number of standards deviations X Numbers of simulations) where each row is just
np.random.normal(0, scale=np.array(standard_deviation)[i], size= (1,number_of_simulations)
I think I could do a loop and then concatenate each result but i don't want to do this if not necessary because you loose the interest of Numpy and Pandas by doing loops I believe.
I hope I was clear and thanks for your help !
CodePudding user response:
The NumPy random functions do accept arrays, but when you also give a size
parameter, the shapes must be compatible.
Change this:
np.random.normal(0, scale=np.array(standard_deviation), size=(len(np.array(standard_deviation)), number_of_simulations)
to
np.random.normal(0, scale=standard_deviation, size=(number_of_simulations, len(standard_deviation)))
The result will have shape (number_of_simulations, len(standard_deviation))
.
Here's a concrete example in an ipython session. Note that instead of using numpy.random.normal
, I use the newer NumPy random API, in which I create a generator called rng
and call its normal()
method:
In [103]: rng = np.random.default_rng()
In [104]: standard_deviation = np.array([1, 5, 25])
In [105]: number_of_simulations = 6
In [106]: rng.normal(scale=standard_deviation, size=(number_of_simulations, len(standard_deviation)))
Out[106]:
array([[ -0.31088926, 1.95005394, -8.77983357],
[ 1.80907248, 4.27082827, 31.13457498],
[ -0.27178958, -12.6589072 , -31.70729135],
[ 0.2848883 , 1.71198071, -23.6336055 ],
[ 0.78457822, 2.78281586, 32.61089728],
[ -0.7014944 , 5.47845616, 5.34276638]])