What are random numbers in NumPy?
Overview
A random number is a number that cannot be predicted logically. A random number does not necessarily mean a different number each time.
Note: Any random number generated through any generation algorithm is called a pseudo-random number. This is because the algorithm can repeat the sequence, and the numbers are not entirely random.
Bearing that in mind, we can say that a program written to generate a random number is never truly random.
In this shot, we’ll take a look at how to generate pseudo-random numbers.
To generate a pseudo-random number in NumPy, we will need the random module offered by NumPy.
Example
In the code below, we will generate a pseudo-random integer between 0 and 10:
# importing the random module from numpyfrom numpy import random# using the randit() method to generate random integers from 0 to 10x = random.randint(10)# printing the random numbersprint(x)
Code explanation
- Line 2: We import the
randommodule fromNumPy. - Line 5: We generate a random integer number between
0and10using therandit()function. - Line 8: We print the pseudo-random number.
Note: The
randint()function is used to generate pseudo-random integers.
Let’s take a look at another example.
Example
In the code below, we want to use the rand() function to generate a pseudo-random float number between 0 and 1.
# importing the random module from numpyfrom numpy import random# using the rand() method to generate random integers from 0 to 10x = random.rand(1)# printing the random float numbersprint(x)
Code explanation
- Line 2: We import the
randommodule fromNumPy. - Line 5: We generate a random float number between
0and1using therand()function. - Line 8: We print the pseudo-random float number.
Note: The
rand()function is used to generate pseudo-random float numbers.