Home > Backend Development > Python Tutorial > How to Generate Random Numbers with a Specified Numerical Distribution in Python?

How to Generate Random Numbers with a Specified Numerical Distribution in Python?

Barbara Streisand
Release: 2024-11-11 04:43:02
Original
579 people have browsed it

How to Generate Random Numbers with a Specified Numerical Distribution in Python?

Generating Random Numbers with Specified Numerical Distribution

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
Copy after login

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])
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template