简体   繁体   中英

Generating an NxM array of uniformly distributed random numbers over a stated interval (not [0,1)) in numpy

I am aware of the numpy.random.rand() command, however there doesn't seem to be any variables allowing you to adjust the uniform interval in which the numbers are chosen to something other than [0,1).

I considered using a for loop ie initiating a zero array of the needed size, and using numpy.random.unifom(a,b,N) to generate N random numbers in the interval (a,b), and then putting these into the initiated array. I am not aware of this module being to create an array of arbitrary dimension, like the rand above. This is clearly inelegant, although y main concern is the run time. I presume this method would have a much higher run time than using the appropriate random number generator from the start.

Edit and additional thought: the interval I am working in is [0,pi/8) which is less than 1. Strictly speaking, I won't be affecting the randomness of the generated numbers if I just rescale, but multiplying each generated random number would clearly be additional computational time, I presume by a factor the order of the number of elements.

np.random.uniform accepts a low and a high:

In [11]: np.random.uniform(-3, 3, 7)  # 7 numbers between -3 and 3
Out[11]: array([ 2.68365104, -0.97817374,  1.92815971, -2.56190434,  2.48954842, -0.16202127, -0.37050593])

numpy.random.uniform accepts a size argument where you can just pass the size of your array as tuple. For generating an MxN array use

np.random.uniform(low,high, size=(M,N))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM