Random Numbers in Python: Riya Jacob K Dept of BCA 2020 - 21
Random Numbers in Python: Riya Jacob K Dept of BCA 2020 - 21
in
Python
Riya Jacob K
Dept of BCA
2020 -21
What is a Random Number?
• Random number does NOT mean a different
number every time.
Integers
• The randint() method takes a size parameter where you can
specify the shape of an array.
Example
• Generate a 1-D array containing 5 random integers from 0
to 100:
from numpy import random
x=random.randint(100, size=(5))
print(x)
Output
[2 5 6 14 92]
Generate 2D Integer Random Array
• Example
Generate a 2-D array with 3 rows, each row
containing 5 random integers from 0 to 100:
from numpy import random
x = random.randint(100, size=(3, 5))
print(x)
• Output
[[90 99 11 30 34]
[66 40 63 36 37]
[63 35 89 51 58]]
Generate 1D Float Random Array
• The rand() method also allows you to specify the shape
of the array.
• Example
Generate a 1-D array containing 5 random floats:
from numpy import random
x = random.rand(5)
print(x)
Output
[0.4305005 0.1667810 0.9989659 0.4566901
0.3199066]
Generate 2D Float Random Array
• Example
Generate a 2-D array with 3 rows, each row
containing 5 random numbers:
from numpy import random
x = random.rand(3, 5)
print(x)
• Output
• [[0.14252791 0.44691071 0.59274288 0.73873487 0.22082345]
[0.00484242 0.36294206 0.88507594 0.56948479 0.15075563]
[0.69195833 0.75111379 0.92780785 0.57986471 0.6203633 ]]
Generate Random Number From Array
• Example
• Generate a 2-D array that consists of the values in the
array parameter (3, 5, 7, and 9):
from numpy import random
x = random.choice([3, 5, 7, 9], size=(3, 5))
print(x)
• Output
[[5 9 7 5 9]
[3 7 7 9 7]
[3 7 9 9 5]]
Random Module-Functions
Thank You