使用权重分布整数?如何计算?

But*_*840 5 python algorithm

我需要根据一些权重分配一个值。例如,如果我的权重是 1 和 2,那么我希望权重为 2 的列的值是权重为 1 的列的两倍。

我有一些 Python 代码来演示我正在尝试做什么,以及问题:

def distribute(total, distribution):
    distributed_total = []
    for weight in distribution:
        weight = float(weight)
        p = weight/sum(distribution)
        weighted_value = round(p*total)
        distributed_total.append(weighted_value)
    return distributed_total

for x in xrange(100):
    d = distribute(x, (1,2,3))
    if x != sum(d):
        print x, sum(d), d
Run Code Online (Sandbox Code Playgroud)

上面的代码显示了许多情况,其中分配值会导致分配的总和与原始值不同。例如,分配权重为 (1,2,3) 的 3 结果为 (1,1,2),总共为 4。

修复此分布算法的最简单方法是什么?

更新:

我希望分布值是整数值。只要整数的总和为正确的值,并且它们“尽可能接近”正确的分布,那么整数的确切分布并不重要。

(正确分布是指非整数分布,我还没有完全定义“尽可能接近”的意思。也许有几个有效的输出,只要它们是原始值的总和。)

Joh*_*hin 9

按预期分配第一股。现在你遇到了一个更简单的问题,参与者减少了,可分配的数量也减少了。重复直到不再有参与者。

>>> def distribute2(available, weights):
...     distributed_amounts = []
...     total_weights = sum(weights)
...     for weight in weights:
...         weight = float(weight)
...         p = weight / total_weights
...         distributed_amount = round(p * available)
...         distributed_amounts.append(distributed_amount)
...         total_weights -= weight
...         available -= distributed_amount
...     return distributed_amounts
...
>>> for x in xrange(100):
...     d = distribute2(x, (1,2,3))
...     if x != sum(d):
...         print x, sum(d), d
...
>>>
Run Code Online (Sandbox Code Playgroud)