NumPy Tutorial NumPy Statistics NumPy References

NumPy - random.sample() function



The NumPy random.sample() 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.sample() + a

Syntax

numpy.random.sample(size=None)

Parameters

size Optional. Specify output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

Return Value

Returns random values in a given shape (unless size=None, in which case a single float is returned).

Example:

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

import numpy as np

x = np.random.sample()

#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.sample((5, 3))

#printing x
print(x)

The output of the above code will be:

[[0.83427982 0.14928282 0.63731192]
 [0.65008078 0.18633094 0.18742767]
 [0.61075212 0.01129346 0.11458491]
 [0.99085745 0.28475412 0.19810717]
 [0.51604249 0.42201909 0.09791535]]

Example:

By using (b-a) * np.random.sample() + 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.sample((5, 3)) + 10

#printing x
print(x)

The output of the above code will be:

[[14.5350012  11.50377783 13.98438303]
 [14.23121651 18.92345323 13.35319144]
 [18.98417555 18.79124236 18.35668005]
 [12.79211314 11.84763782 16.63781161]
 [11.86143982 19.85435164 13.33015107]]

❮ NumPy - Random

5