This article addresses the challenge of generating random numbers based on a given distribution. In particular, the focus is on a specific distribution as outlined in the input:
1 0.1 2 0.05 3 0.05 4 0.2 5 0.4 6 0.2
It is possible to develop a customized solution for generating random numbers according to the given distribution. This involves creating the cumulative density function and selecting the corresponding value based on a randomly generated value between 0 and 1. However, numerous existing modules can simplify this task, eliminating the need for manual coding.
One such module is scipy.stats.rv_discrete, which allows you to specify probabilities through its values parameter. To generate random numbers, you can call the rvs() method of the distribution object.
Another option is to use the numpy.random.choice() function. It accepts a list of values and assigns probabilities using the p keyword parameter. For instance:
numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])
For Python 3.6 and above, you can leverage random.choices() from the standard library. Here's an example:
import random random.choices(range(1, 7), weights=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])
The above is the detailed content of How to Generate Random Numbers with a Specific Distribution in Python?. For more information, please follow other related articles on the PHP Chinese website!