Choosing n numbers with fixed sum

我们两清 提交于 2019-11-26 14:38:19

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.

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.

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.

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