Probability selection algorithm
Noah
noah at noah.org
Fri Feb 7 03:03:41 EST 2003
Paul Rubin <phr-n2003b at NOSPAMnightsong.com> wrote in message news:<7xhebnscrj.fsf at ruckus.brouhaha.com>...
> Paul Rubin <phr-n2003b at NOSPAMnightsong.com> writes:
> ...
> Again, this depends on your probability list adding up to 1.
> Otherwise, add up the probabilities and scale everything appropriately.
It also depends on the probability list being sorted, but
I may have implied that the list is sorted in my original post.
random.random() does what you want from urand().
I wrote the following demo based on your code.
This seems to do everything I need. Thanks!
Let me know if you see any mistakes.
Yours,
Noah
#!/usr/bin/env python
import random
from pprint import pprint
def make_random_probabilities_table ():
"""This creates a table of random probabilities that add up to 1.0.
The table is a random size from 1 through 10.
The table is sorted.
"""
t = []
count = random.randint (0, 9)
total = 1.0
for c in range (count):
r = random.uniform (0.0, total)
t.append(r)
total = total - r
t.append (total)
t.sort ()
return t
def random_select (problist):
"""This selects one of the odds from the problist table weighted
on the probabilities in the table.
The table must be sorted.
"""
remaining = 1.0
r = random.random()
for i in range(len(problist)):
p = problist[i]
if r * remaining < p:
return (r, i, p)
remaining -= p
def main ():
odds = make_random_probabilities_table ()
(r, i, p) = random_select (odds)
pprint (odds)
print 'random number =', r
print 'index =', i
print 'probability =', p
if __name__ == '__main__':
main ()
More information about the Python-list
mailing list