random.choice с вероятностью

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def choice_equel(system):
    p = [
            sum([item[-1] for item in system[:count + 1]])
            for count in range(len(system))
        ]
    i = random.random()
    pt = [i < pi for pi in p]
    return pt.index(True)

#пример системы из которой нужно выбирать элементы с заданой вероятностью
system = [
        (0.824074, 0.281482, -0.212346, 0.864198, -1.882290, -0.110607, 0.787473),
        (0.088272, 0.520988, -0.463889, -0.377778, 0.785360, 8.095795, 0.212527)
    ]
#первый элемент нужно выбрать с вероятностью 0.787473,
#второй с вероятностью 0.212527

#проверяем работу функции
counts = {index: 0 for index in range(len(system))}
for _ in range(1000000):
    counts[choice_equel(system)] += 1
print counts
#результат {0: 787367, 1: 212633}
4 апреля 2012, 14:49 1 alexey-grom
blog comments powered by Disqus