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:
scipy.stats.rv_discrete:
numpy.random.choice() with p parameter:
Example:
numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])
random.choices() (Python 3.6 ):
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!