Curriculum
Course: NumPy
Login

Curriculum

NumPy

Text lesson

Random Distribution

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.

Example

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:

  • 3 appears with a probability of 0.1,
  • 5 appears with a probability of 0.3,
  • 7 appears with a probability of 0.6,
  • 9 does not appear at all (probability of 0).
from numpy import random

x = random.choice([3579], p=[0.10.30.60.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.

Example

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([3579], p=[0.10.30.60.0], size=(35))

print(x)