Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate n dimensional random variables in a specific range in python

I want to generate uniform random variables in the range of [-10,10] of various dimensions in python. Numbers of 2,3,4,5.... dimension.

I tried random.uniform(-10,10), but that is only one dimensional. I do not know how to do it for n-dimension. By 2 dimension I mean,

[[1 2], [3 4]...]
like image 721
gizgok Avatar asked Mar 04 '13 04:03

gizgok


1 Answers

Since numpy is tagged, you can use the random functions in numpy.random:

>>> import numpy as np
>>> np.random.uniform(-10,10)
7.435802529756465
>>> np.random.uniform(-10,10,size=(2,3))
array([[-0.40137954, -1.01510912, -0.41982265],
       [-8.12662965,  6.25365713, -8.093228  ]])
>>> np.random.uniform(-10,10,size=(1,5,1))
array([[[-3.31802611],
        [ 4.60814984],
        [ 1.82297046],
        [-0.47581074],
        [-8.1432223 ]]])

and modify the size parameter to suit your needs.

like image 128
DSM Avatar answered Sep 20 '22 20:09

DSM