How to generate random numbers with a given (numerical) distribution with Python?

Sometimes, we want to generate random numbers with a given (numerical) distribution with Python.

In this article, we’ll look at how to generate random numbers with a given (numerical) distribution with Python.

How to generate random numbers with a given (numerical) distribution with Python?

To generate random numbers with a given (numerical) distribution with Python, we can use the choice function from the random module.

For instance, we write:

from random import choices

population = [1, 2, 3, 4, 5, 6]
weights = [0.1, 0.05, 0.05, 0.2, 0.4, 0.2]
num = choices(population, weights)
print(num)

We call choices with the population list which we draw numbers from and the weights list which are numerical distribution of each value.

The returned number is assigned to num.

Conclusion

To generate random numbers with a given (numerical) distribution with Python, we can use the choice function from the random module.