NumPy Tutorial NumPy Statistics NumPy References

NumPy - random.rand() function



The NumPy random.rand() function returns random values in a given shape. The function creates an array of the given shape and populate it with random samples drawn from continuous uniform distribution over [0, 1).

For generating random values from unif[a, b), b>a, the following relationship can be used:

(b-a) * np.random.rand() + a

Syntax

numpy.random.rand(d0, d1, ..., dn)

Parameters

d0, d1, ..., dn Optional. Specify dimensions of the returned array, should all be positive. If no argument is given a single Python float is returned.

Return Value

Returns random values in a given shape.

Example:

In the example below, random.rand() function is used to generate a single random value.

import numpy as np

x = np.random.rand()

#printing the random number
print("x =", x)

The output of the above code will be:

x = 0.22076149806948886

Example:

In the example below, the function is used to generate random values in the specified shape.

import numpy as np

#creating an array of given size
#filled with random numbers
x = np.random.rand(5, 3)

#printing x
print(x)

The output of the above code will be:

[[0.76503505 0.29506873 0.20241422]
 [0.66315398 0.54226745 0.11124589]
 [0.12117752 0.72995682 0.3798694 ]
 [0.45234472 0.67215523 0.90047342]
 [0.24848435 0.49199304 0.32012145]]

Example:

By using (b-a) * np.random.rand() + a relationship, we can define the uniform distribution to the draw the sample from.

import numpy as np

#creating an array of given size filled with
#random numbers drawn from [10, 20)
x = (20-10) * np.random.rand(5, 3) + 10

#printing x
print(x)

The output of the above code will be:

[[11.22009821 19.53731226 15.79550244]
 [15.08270698 11.23815332 17.25568115]
 [19.32902131 12.50019709 17.74865773]
 [11.4636353  14.04455759 10.08556483]
 [12.26902599 19.80255263 12.60528569]]

❮ NumPy - Random