Saturday, June 13, 2020

Numpy Random Number

Numpy Random Number

A Random Number

A random number is something that is logically unpredictable. It does not mean a different number every time. Programmatically, random numbers can be categorized into two categories.

  • Pseudo-Random numbers
  • True Random numbers
The computing devices execute programs written by the programmers, and these programs are a conclusive set of instructions. It means that there is some algorithm to produce a random number too.

However, this program to generate a random number can be predicted, it means that this number is not a true random number.  The random numbers generated using some generation algorithm is known as pseudo-random numbers.

To generate a truly random number, it is necessary to get the random data from some explicit sources such as keyboard keystrokes, mouse impressions, any random data available on the network, etc.

It is not necessary to use truly random numbers unless it is associated with any security (such as encryption keys etc.) or the basis of application is the randomness (such as Digital roulette wheels etc.).

We are concerned with pseudo-random numbers using Numpy in this article.

Numpy random Module

The random module from the Numpy library can be used to generate random numbers.

For example

from numpy import random

num = random.randint(50)


The randint() method in the above code will produce a random number between 0 to 50.
We can also generate a random float number using the rand() method.

from numpy import random
#generate a float number between 0 and 1
num = random.rand()


Generating Random Number Arrays

The randint() method can be used to generate an array containing random numbers of a specified size.

For example,

from numpy import random
#generate an array of integers
num = random.randint(100, size=(6))


[18 70 33 87 12 37]

To generate a 2-D array containing random numbers,

from numpy import random
#generate a 2-D array of integers
num = random.randint(100, size=(3, 3))


[[93 48 16]
 [42 87 98]
 [ 4 29 93]]

Same can be done with rand() method to generate floating number arrays,
For example,

from numpy import random
#generate a arrays of floats
num1D = random.rand(6)
num2D = random.rand(3, 3)



[0.81955336 0.84469223 0.29665967 0.81502409 0.18450341 0.37109707]
[[0.47840853 0.8892987  0.38056846]
 [0.04916841 0.25365781 0.92287297]
 [0.31012879 0.47607149 0.77779443]]

Generating Random Number from an Array

The choice method can be used to select a number from a given array randomly.

from numpy import random
#choice method
num = random.choice([3,12,5,7,11,8,23])