Numpy Random

In NumPy, we have a module called random which provides functions for generating random numbers.

These functions can be useful for generating random inputs for testing algorithms.


Generate Random Integer in NumPy

As discussed earlier, we use the random module to work with random numbers in NumPy.

Let's see an example.

In this example, we have used the random module to generate a random number. The random.randint() function takes two arguments,

  • 0 - a lower bound (inclusive)
  • 10 - an upper bound (exclusive)

Here, random.randint() returns a random integer between 0 and 9.

Since the output will be a randomly generated integer between 0 and 9, we will see different outputs each time the code is run.

Note: We can also import and use the random module like this:

Here, the syntax is slightly different but the output will be the same as above, we will get a random integer between 0 and 9.


Generate Random Float in NumPy

We can also generate a random floating-point number between 0 and 1. For that we use the random.rand() function. For example,

Here, random.rand() generates a random floating-point number between 0 and 1.

Since the number is generated randomly, the output value can vary each time the code is run.


Generate Random Array in NumPy

NumPy's random module can also be used to generate an array of random numbers. For example,

Output

1D Random Integer Array:
[9 7 8 4 2]

1D Random Float Array:
 [0.7877579  0.01723754 0.93995075 0.17126388 0.69913594]

2D Random Integer Array:
 [[0 5 3 8]
 [3 9 2 1]
 [8 7 1 2]]

Here,

  • np.random.randint(0, 10, 5) - generates a 1D array of 5 random integers between 0 and 9.
  • np.random.rand(5) - generates a 1D array of 5 random numbers between 0 and 1.
  • np.random.randint(0, 10, (3,4)) - generates a 2D array of shape (3, 4) with random integers between 0 and 9.

Choose Random Number from NumPy Array

To choose a random number from a NumPy array, we can use the random.choice() function.

Let's see an example.

In the above example, the np.random.choice(array1) function chooses a random number from the array1 array.

It is important to note that the output will be a single random number from array1, which will be different each time the code is run.