Probability distribution in Python

后端 未结 12 2065
误落风尘
误落风尘 2020-12-02 08:12

I have a bunch of keys that each have an unlikeliness variable. I want to randomly choose one of these keys, yet I want it to be more unlikely for unlikely (key, values) to

12条回答
  •  臣服心动
    2020-12-02 08:51

    The simplest thing to do is to use random.choice (which uses a uniform distribution) and vary the frequency of occurrence on the object in the source collection.

    >>> random.choice([1, 2, 3, 4])
    4
    

    ... vs:

    >>> random.choice([1, 1, 1, 1, 2, 2, 2, 3, 3, 4])
    2
    

    So your objects could have a base occurrence rate (n) and between 1 and n objects are added to the source collection as a function of the conviction rate. This method is really simple; however, it can have significant overhead if the number of distinct objects is large or the conviction rate needs to be very fine grained.

    Alternatively, if you generate more that one random number using a uniform distribution and sum them, numbers occurring near the mean are more probable that those occurring near the extremes (think of rolling two dice and the probability of getting 7 versus 12 or 2). You can then order the objects by conviction rate and generate a number using multiple die rolls which you use to calculate and index into the objects. Use numbers near the mean to index low conviction objects and numbers near the extremes to index high conviction items. You can vary the precise probability that a given object will be selected by changing the "number of sides" and number of your "dice" (it may be simpler to put the objects into buckets and use dice with a small number of sides rather than trying to associate each object with a specific result):

    >>> die = lambda sides : random.randint(1, sides)
    >>> die(6)
    3
    >>> die(6) + die(6) + die(6)
    10
    

提交回复
热议问题