Random selection

T

Tartifola

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
 
P

Peter Otten

Tartifola said:
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 += 1
print histo
 
R

Roger Miller

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top