What is a Random Number?
A random number is one that cannot be predicted logically.
It doesn’t just mean a different number every time—it means the result is unpredictable.
Pseudo Random vs. True Random
Computers follow instructions through programs. This means numbers generated by a computer are based on algorithms. As a result, random numbers generated by such algorithms can technically be predicted, making them pseudo-random.
Pseudo-random numbers are generated using formulas or algorithms and are not truly random, though they are sufficient for most tasks.
However, true random numbers can be generated by using data from unpredictable physical sources, such as:
Keyboard inputs
Mouse movements
Network traffic
These sources provide randomness that cannot be reproduced by a program.
True random numbers are generally needed in areas like:
Cryptography (for encryption keys)
Applications where absolute unpredictability is required (e.g., digital roulette wheels).
For most everyday uses, pseudo-random numbers are more than enough.
Generating Random Numbers with NumPy
NumPy has a random module for working with random numbers.
Generate Random Integer
program:
Generate a random integer between 0 and 10
from numpy import random
x = random.randint(100)
print(x)
Output:
Generate Random Float
Program:
Generate a random float between 0 and 1
from numpy import random
x = random.rand()
print(x)
Output:
Generating Random Arrays
Since NumPy works with arrays, you can easily create random arrays.
Random Integers
Program:
Generate a 1-D array with 5 random integers from 0 to 100:
from numpy import random
x = random.randint(100, size=(5))
print(x)
Output:
Program:
Generate a 2-D array with 3 rows and 5 random integers in each row:
from numpy import random
x = random.randint(100, size=(3, 5))
print(x)
Output:
Random Floats
Program:
Generate a 1-D array with 5 random floats:
from numpy import random
x = random.rand(5)
print(x)
Output:
Program:
Generate a 2-D array with 3 rows and 5 random floats in each row:
from numpy import random
x = random.rand(3, 5)
print(x)
Output:
Selecting Random Values from an Array
The choice() method allows you to randomly select values from a given array.
Program:
Select One Random Value
Select one random value from an array:
from numpy import random
x = random.choice([3, 5, 7, 9])
print(x)
Output:
Program:
Select Multiple Random Values
Create a 2-D array with random choices from a given list:
from numpy import random
x = random.choice([3, 5, 7, 9], size=(3, 5))
print(x)