By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,846 Members | 1,862 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,846 IT Pros & Developers. It's quick & easy.

Random selection

P: n/a

Hi,
I have a list with probabilities as elements

[p1,p2,p3]

with of course p1+p2+p3=1. I'd like to draw a
random element from this list, based on the probabilities contained in
the list itself, and return its index.

Any help on the best way to do that?
Thanks
May 18 '07 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Tartifola wrote:
I have a list with probabilities as elements

[p1,p2,p3]

with of course p1+p2+p3=1. I'd like to draw a
random element from this list, based on the probabilities contained in
the list itself, and return its index.

Any help on the best way to do that?
import random
import bisect

def draw(probabilities):
sigma = 0.0
ps = []
for p in probabilities:
sigma += p
ps.append(sigma)

_bisect = bisect.bisect
_random = random.random
while 1:
yield _bisect(ps, _random())

if __name__ == "__main__":
from itertools import islice
histo = [0]*4
for i in islice(draw([0.2, 0.3, 0.5]), 100000):
histo[i] += 1
print histo
May 18 '07 #2

P: n/a
On May 17, 10:39 pm, Tartifola <tartif...@gmail.comwrote:
Hi,
I have a list with probabilities as elements

[p1,p2,p3]

with of course p1+p2+p3=1. I'd like to draw a
random element from this list, based on the probabilities contained in
the list itself, and return its index.

Any help on the best way to do that?
Thanks
This of course depends on your definition of "best". There is a fast
and simple technique if all probabilities are multiples of 1/n for a
reasonably small n, or if you are willing to round them to such.
Suppose for example that the probabilities are [0.42, 0.23, 0.35].
Create a list of 100 items with 42 0's, 23 1's, and 35 2's, then
select a random element using random.choice() or
equivalent.

May 18 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.