2

I recently came across the following use of numpy from this link numpy randint manual. The last example in this page shows this command with no explanation.

import numpy
x=numpy.random.randint([1, 3, 5, 7], [[10], [20]], dtype=np.uint8)

Can you please explain what does the input argument mean?

Aleph
  • 224
  • 1
  • 11

2 Answers2

2

When the two arrays [1, 3, 5, 7] and [[10], [20]] are broadcast to a common shape, the first one becomes

[[1, 3, 5, 7]
 [1, 3, 5, 7]]

and the second gives

[[10, 10, 10, 10]]
 [20, 20, 20, 20]]

np.random.randint() produces a randomly generated array of integers of the same shape as these arrays, where each entry is bound by the corresponding entries of the two arrays. For example, the entry in the position (0, 0) will be at least 1 and smaller than 10, the entry in the position (0, 1) will be at least 3 and smaller than 10 etc.

bb1
  • 7,174
  • 2
  • 8
  • 23
1
In [25]: x=np.random.randint([1, 3, 5, 7], [[10], [20]], dtype=np.uint8)
In [26]: x.shape
Out[26]: (2, 4)

The 2 inputs are a (4,) and (2,1) shaped arrays:

In [27]: np.array([1, 3, 5, 7]), np.array([[10], [20]])
Out[27]: 
(array([1, 3, 5, 7]),
 array([[10],
        [20]]))

By broadcasting rules

(4,) with (2,1) => (1,4) with (2,1) => (2,4)
  • add leading size 1 dimensions as needed
  • scalar all size 1 dimensions to match

In this case

In [28]: x
Out[28]: 
array([[ 6,  9,  7,  9],
       [19, 17, 10,  9]], dtype=uint8)

By column, values are all >= than [1,3,5,7], right?

And by row, the upper bounds are [10, 20], right?

A couple sample arrays:

In [29]: x=np.random.randint([1, 3, 5, 7], [[10], [20]], dtype=np.uint8)
In [30]: x
Out[30]: 
array([[ 7,  8,  5,  9],
       [ 5, 17,  6,  9]], dtype=uint8)
In [31]: x=np.random.randint([1, 3, 5, 7], [[10], [20]], dtype=np.uint8)
In [32]: x
Out[32]: 
array([[ 6,  9,  7,  9],
       [ 9, 11, 18, 10]], dtype=uint8)
hpaulj
  • 221,503
  • 14
  • 230
  • 353