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

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

Susan Sarandon
Release: 2024-11-10 17:28:02
Original
696 people have browsed it

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

Generating Random Numbers with a Specified (Numerical) Distribution

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

Existing Modules for Distribution-Based Random Number Generation

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.

scipy.stats.rv_discrete

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.

numpy.random.choice()

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

random.choices()

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

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!

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