How to Generate Weighted Random Numbers in Python



In this article, you will learn how to generate weighted random numbers in Python.

Generate weighted random numbers

To generate weighted random numbers in Python, you can use the random.choices() function from the Python standard library. This function takes a list of values and their corresponding weights, and returns a randomly chosen value according to the specified weights.

Here’s an example:

import random

values = [1, 2, 3, 4]
weights = [0.1, 0.3, 0.5, 0.1]

random_number = random.choices(values, weights=weights)[0]

In this example, the values list contains the values to choose from, and the weights list contains the corresponding weights for each value. The random.choices() function selects a value randomly based on its weight, and returns a list containing the chosen value. The [0] at the end is used to extract the first element from the list, which is the randomly chosen value.

In this case, the output could be different each time the code is run, but it will tend to favor the value 3 since it has the highest weight.