Home  >  Article  >  Backend Development  >  How to Generate Random Numbers with a Custom Distribution in Python?

How to Generate Random Numbers with a Custom Distribution in Python?

Susan Sarandon
Susan SarandonOriginal
2024-11-10 19:03:02467browse

How to Generate Random Numbers with a Custom Distribution in Python?

Generating Random Numbers Using a Specific Distribution

You possess a file containing probabilities for distinct values:

1 0.1
2 0.05
3 0.05
4 0.2
5 0.4
6 0.2

Your goal is to generate random numbers based on this distribution. You seek an existing module capable of handling this task, recognizing that it is a prevalent issue that may have already prompted the development of specialized functions or modules.

Solution

The Python ecosystem provides several options for generating random numbers with a specific distribution:

  1. scipy.stats.rv_discrete:

    • Supply your probabilities within the values parameter.
    • Utilize the rvs() method of the distribution object to generate random numbers.
  2. numpy.random.choice() with p parameter:

    • Pass the probabilities as the p keyword parameter.
    • Example:

      numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])
  3. random.choices() (Python 3.6 ):

    • This function from the standard library allows for specifying probabilities.
    • Example:

      import random
      random.choices(population=list(range(1, 7)), weights=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])

These modules provide efficient and straightforward ways to generate random numbers with a given distribution, eliminating the need to implement custom algorithms.

The above is the detailed content of How to Generate Random Numbers with a Custom Distribution in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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