Can I generate an array with both negative and positive numbers and specify the limits and the dimension of this array?

18,205

Solution 1

Use np.random.randint and pass the size parameter. For values in [-2, 2) and size (10, 2) you have:

In [32]: np.random.randint(-2, 2, (10, 2))
Out[32]:
array([[-1,  1],
       [-2,  0],
       [-1,  0],
       [-2, -2],
       [ 0, -2],
       [-2, -2],
       [ 0,  0],
       [ 1, -1],
       [ 0,  1],
       [-2, -1]])

Or use np.random.uniform for floats:

In [33]: size = (10, 2)

In [39]: np.random.uniform(-2, 2, size)
Out[39]:
array([[-1.1129566 , -1.94562947],
       [ 0.21356557, -1.96769933],
       [ 1.1481992 , -0.08494563],
       [ 0.12561175,  0.95580417],
       [-1.79335536, -1.01276994],
       [ 1.56808971,  0.15911181],
       [ 0.50987451, -1.39039728],
       [-1.57962641,  1.59555514],
       [-1.8318709 , -1.57055885],
       [ 0.682527  , -1.89022731]])

Solution 2

If you don't want to generate uniform numbers from a normal distribution you could get a random number between 0 and 1, and the use that to build your random number between the min and max.

(np.random.rand(30) * 10) - 5

The above will give 30 numbers between [-5, +5)

Share:
18,205
van boeren
Author by

van boeren

Updated on June 15, 2022

Comments

  • van boeren
    van boeren almost 2 years

    c=np.random.rand(10,2) generates an array of random numbers from in [0,1). Can I generate the same array (in terms of size) but with negative AND positive numbers? Moreover, can I choose the limits and the dimension of this array? for example if I want from -2 to 2.

  • Martijn Pieters
    Martijn Pieters over 7 years
    This only generates integers, I think the OP wanted floats.
  • Martijn Pieters
    Martijn Pieters over 7 years
    Granted, not sure what I based that on now.
  • Moses Koledoye
    Moses Koledoye over 7 years
    @MartijnPieters I added some code that can help them get floats from those
  • Moses Koledoye
    Moses Koledoye over 7 years
    @MartijnPieters Brainfart on that. Was trying to retrofit the first answer to match the float requirement
  • Martijn Pieters
    Martijn Pieters over 7 years
    Take into account uniform is half-open; you can produce -2, but never 2. You could use -2 + sys.float_info.epsilon to 'open' the start..
  • Moses Koledoye
    Moses Koledoye over 7 years
    @MartijnPieters Yes thanks for suggesting that workaround. I indicated the half openness with [-2, 2) in the answer.
  • seralouk
    seralouk about 4 years
    I need to generate an array n x n with negative values between -0.35 and -0.30. How can I do that?