Generating random no.-
The random module of numpy library is used to generate random nos. in python.
from numpy import random
x = random.randint(10)
print(x)
Output- 5
It will generate a random integer from 0 to 10.
Generating random float-
The rand() method returns a random float between 0 and 1.
from numpy import random
x = random.rand()
print(x)
Output-
0.5237585580539366
Generating random array-
The randint() method takes a size parameter where we can specify the shape of an array.
Generating a 1-D array having 3 random integers from 0 to 10-
from numpy import random
x=random.randint(10, size=(3))
print(x)
Output-
[3 8 2]
Generating a 2-D array with 2 rows, each row containing 3 random integers from 0 to 10-
from numpy import random
x = random.randint(10, size=(2, 3))
print(x)
Output-
[[1 2 7]
[1 3 6]]
Generating float arrays-
The rand() method with the specified shape of the array is used to generate float array.
Generating 1-D float array-
from numpy import random
x = random.rand(5)
print(x)
Output-
[0.6918126 0.3412298 0.4600709 0.2848470 0.8970721]
Generate a 2-D array with 3 rows, each row containing 2 random numbers-
from numpy import random
x = random.rand(3, 2)
print(x)
Output-
[[0.95172221 0.31537368]
[0.17274886 0.87510511]
[0.74709024 0.17880643]]
Generating random number from array-
The choice() method is used to generate the random value from the array passed to it. It takes an array as a parameter and randomly returns one of the values.
from numpy import random
x = random.choice([1, 2, 3])
print(x)
Output-
3
The choice() method also allows us to return an array of values. Add a size parameter to specify the shape of the array as shown in following example-
Generate a 2-D array that consists of the values in the array parameter (1, 2, 3, and 4)
from numpy import random
x = random.choice([1, 2, 3, 4], size=(2, 3))
print(x)
Output-
[[4 4 1]
[4 2 4]]
Leave a Reply