Generate random numbers with a given (numerical) distribution

前端 未结 13 2217
我寻月下人不归
我寻月下人不归 2020-11-22 11:18

I have a file with some probabilities for different values e.g.:

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

I would like to generate random numb

13条回答
  •  不要未来只要你来
    2020-11-22 11:58

    Since Python 3.6, there's a solution for this in Python's standard library, namely random.choices.

    Example usage: let's set up a population and weights matching those in the OP's question:

    >>> from random import choices
    >>> population = [1, 2, 3, 4, 5, 6]
    >>> weights = [0.1, 0.05, 0.05, 0.2, 0.4, 0.2]
    

    Now choices(population, weights) generates a single sample:

    >>> choices(population, weights)
    4
    

    The optional keyword-only argument k allows one to request more than one sample at once. This is valuable because there's some preparatory work that random.choices has to do every time it's called, prior to generating any samples; by generating many samples at once, we only have to do that preparatory work once. Here we generate a million samples, and use collections.Counter to check that the distribution we get roughly matches the weights we gave.

    >>> million_samples = choices(population, weights, k=10**6)
    >>> from collections import Counter
    >>> Counter(million_samples)
    Counter({5: 399616, 6: 200387, 4: 200117, 1: 99636, 3: 50219, 2: 50025})
    

提交回复
热议问题