Generate random numbers with a given (numerical) distribution

前端 未结 13 2200
我寻月下人不归
我寻月下人不归 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:48

    Another answer, probably faster :)

    distribution = [(1, 0.2), (2, 0.3), (3, 0.5)]  
    # init distribution  
    dlist = []  
    sumchance = 0  
    for value, chance in distribution:  
        sumchance += chance  
        dlist.append((value, sumchance))  
    assert sumchance == 1.0 # not good assert because of float equality  
    
    # get random value  
    r = random.random()  
    # for small distributions use lineair search  
    if len(distribution) < 64: # don't know exact speed limit  
        for value, sumchance in dlist:  
            if r < sumchance:  
                return value  
    else:  
        # else (not implemented) binary search algorithm  
    

提交回复
热议问题