1

I want to generate a list of n probabilities with the sum of probabilities amounting to 1. The list is of fixed size, but could be arbitrarily large. So n could be 111, 2, 10, 14, 100, etc. I realize that this might be a computational challenge of sorts and there might not be one best way of doing this but I would still gladly appreciate suggestions for a reasonable approach.

1
  • 1
    What sort of a distribution are you looking for? Obviously a naive way is simply a uniform distribution where each value is 1/n. Commented Nov 27, 2012 at 10:13

2 Answers 2

4

The best way to do this I think is generate a list of random numbers of the desired size, add all numbers and divide every number by the total:

randlist = [randon.random() for i in range(n)]
total = sum(randlist)
randlist = [i/total for i in randlist]
Sign up to request clarification or add additional context in comments.

Comments

1

Similar to Smetterleen but perhaps slightly more efficient:

import random
def generate(n):
    unnormalised = [random.random() for _ in range(n)]
    s = sum(unnormalised)
    normalised = map(lambda x: x/s, unnormalised)
    return normalised

Worth noting that neither of these will necessarily sum to precisely to 1:

>>> sum(generate(4))
1.0
>>> sum(generate(4))
1.0
>>> sum(generate(4))
1.0000000000000002
>>> sum(generate(4))
0.9999999999999999
>>> sum(generate(4))
1.0

1 Comment

more efficient - [random.random() for _ in itertools.repeat(None, n)]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.