A random distribution is a collection of random numbers that adhere to a specific probability density function.
Probability Density Function: A function that defines a continuous probability, representing the likelihood of all values within an array. |
We can generate random numbers based on specified probabilities using the choice()
method from the random module, which allows us to define the probability for each value. Probabilities are assigned values between 0 and 1, where 0 means the value will never occur, and 1 means it will always occur.
Generate a 1-D array containing 100 values, where each value is either 3, 5, 7, or 9. The probabilities for each value are defined as follows:
from numpy import random x = random.choice([3, 5, 7, 9], p=[0.1, 0.3, 0.6, 0.0], size=(100)) print(x) |
Even if you run the above example 100 times, the value 9 will never appear. You can generate arrays of any shape and size by specifying the desired shape in the size parameter.
Use the same example as above, but generate a 2-D array with 3 rows, where each row contains 5 values.
from numpy import random x = random.choice([3, 5, 7, 9], p=[0.1, 0.3, 0.6, 0.0], size=(3, 5)) print(x) |