bisect in python


例えばサンプリングするときに便利かなと思います。

import bisect
import random
import numpy as np

distribution = [0.1, 0.3, 0.2, 0.4]
print 'distrbution: ' + str(distribution)

accumulated = np.add.accumulate(distribution)
print 'accumulated: ' + str(accumulated)

normalized = [float(x)/accumulated[-1] for x in accumulated]
print 'normalized: ' + str(normalized)

rand = random.random()
sample = bisect.bisect(normalized, rand)
print sample # between 0 and 3 in this example.

e.g.
>distrbution: [0.1, 0.3, 0.2, 0.4]
>accumulated: [ 0.1  0.4  0.6  1. ]
>normalized: [0.10000000000000001, 0.40000000000000002, 0.60000000000000009, 1.0]
>1

タグ:

python
最終更新:2016年03月14日 07:15