Home > Article > Backend Development > How to Generate Random Numbers with a Specified Numerical Distribution in Python?
When faced with the task of generating random numbers that adhere to a certain distribution, one may ponder the existence of preexisting modules capable of handling such a task. After all, this is a prevalent problem with a potential solution that has been addressed by numerous programmers.
Consider the following example:
1 0.1 2 0.05 3 0.05 4 0.2 5 0.4 6 0.2
Here, we have a file containing values and their corresponding probabilities. To generate random numbers based on this distribution, we could utilize scipy.stats.rv_discrete. By supplying our probabilities through the values parameter, we can create a distribution object. Subsequenly, we can employ the rvs() method of the distribution object to generate random numbers.
However, another viable option is to use numpy.random.choice(). This function accepts a p keyword parameter, allowing us to specify our probabilities directly.
For instance:
numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])
And finally, for those using Python 3.6 or later, random.choices() from the standard library provides a convenient solution.
The above is the detailed content of How to Generate Random Numbers with a Specified Numerical Distribution in Python?. For more information, please follow other related articles on the PHP Chinese website!