Choosing n numbers with fixed sum

て烟熏妆下的殇ゞ 提交于 2019-12-17 02:49:29

问题


In some code I want to choose n random numbers in [0,1) which sum to 1.

I do so by choosing the numbers independently in [0,1) and normalizing them by dividing each one by the total sum:

numbers = [random() for i in range(n)]
numbers = [n/sum(numbers) for n in numbers]

My "problem" is, that the distribution I get out is quite skew. Choosing a million numbers not a single one gets over 1/2. By some effort I've calculated the pdf, and it's not nice.

Here is the weird looking pdf I get for 5 variables:

Do you have an idea for a nice algorithm to choose the numbers, that result in a more uniform or simple distribution?


回答1:


You are looking to partition the distance from 0 to 1.

Choose n - 1 numbers from 0 to 1, sort them and determine the distances between each of them.

This will partition the space 0 to 1, which should yield the occasional large result which you aren't getting.

Even so, for large values of n, you can generally expect your max value to decrease as well, just not as quickly as your method.




回答2:


You might be interested in the Dirichlet distribution which is used for generate quantities that sum to 1 if you're looking for probabilities. There's also a section on how to generate them using gamma distributions here.




回答3:


Another way to get n random numbers which sum up to 1:

import random


def create_norm_arr(n, remaining=1.0):
    random_numbers = []
    for _ in range(n - 1):
        r = random.random()  # get a random number in [0, 1)
        r = r * remaining
        remaining -= r
        random_numbers.append(r)
    random_numbers.append(remaining)
    return random_numbers

random_numbers = create_norm_arr(5)
print(random_numbers)
print(sum(random_numbers))

This makes higher numbers more likely.



来源:https://stackoverflow.com/questions/5622608/choosing-n-numbers-with-fixed-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!