How to generate random uniform distributed NumPy array?

NumPy provides uniform() function to generate uniformly distributed random numbers. The uniform() function is present in a random module of NumPy.

How to use numpy.random.uniform() in Python?

The syntax of uniform() function is

numpy.random.uniform(lower, upper, size)

It takes three arguments:

  • lower: It is the lower bound. All the numbers generated from uniform() are greater than or equal to lower. Its default value is 0.
  • upper: It is the upper bound. All the numbers generated from uniform() are less than upper. Its default value is 1.
  • size: It is used to specify the shape of the returned NumPy array. If nothing is specified, then a single value is generated. You can pass an integer or a tuple of integers.

In mathematical terms, numbers generated by numpy.random.uniform() function belongs to [lower, upper) interval.

Note: All the numbers between the specified interval have equal probability of occurring. The size parameter controls how many numbers will be generated.

How to generate 1D NumPy array using np.random.uniform()?

import numpy as np
arr = np.random.uniform(0, 10, size=5)
print(arr)

Output

[3.58278693 7.58057951 9.51818642 7.63117296 2.73584315]

The above code will provide a 1 dimensional NumPy array that contains 5 uniformly generated random numbers between 0 and 10.

import numpy as np
arr = np.random.uniform(-1, 1, size=(4))
print(arr)

Output

[-0.17077581 -0.68234879 -0.53202123  0.43884018]

The above code will provide a 1 dimensional NumPy array that contains 4 uniformly generated random numbers between -1 and 1.

How to generate 2D NumPy array using np.random.uniform()?

import numpy as np
arr = np.random.uniform(0, 1, size=(2, 3))
print(arr)

Output

[[0.84666524 0.24250251 0.85863502]
 [0.88411415 0.21698299 0.61560524]]

The above code will generate a 2x3 NumPy array that contains 6 uniformly generated random numbers between 0 and 1.

Recommended Posts