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.
2 Answers
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
alexvassel
more efficient - [random.random() for _ in itertools.repeat(None, n)]
1/n.