分发使用权整数?如何计算? [英] Distributing integers using weights? How to calculate?

查看:139
本文介绍了分发使用权整数?如何计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要分发基于一些权重值。例如,如果我的权重为1和2,然后我希望加权为2列有值权重1列的两倍。

I need to distribute a value based on some weights. For example, if my weights are 1 and 2, then I would expect the column weighted as 2 to have twice the value as the column weighted 1.

我有一些Python code证明什么,我试图做的,而这个问题:

I have some Python code to demonstrate what I'm trying to do, and the problem:

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

有由code以上,其中分发值导致分布的总和比所述原始值不同所示许多情况。例如,具有(1,2,3)的结果(1,1,2)的权重分配3,总共4

There are many cases shown by the code above where distributing a value results in the sum of the distribution being different than the original value. For example, distributing 3 with weights of (1,2,3) results in (1,1,2), which totals 4.

什么是解决这个分发算法的最简单的方法是什么?

What is the simplest way to fix this distribution algorithm?

更新:

我希望分散值是整数值。不要紧究竟如何的整数被分布,只要它们的总为正确的值,并且它们是尽可能接近,以正确的分布。

I expect the distributed values to be integer values. It doesn't matter exactly how the integers are distributed as long as they total to the correct value, and they are "as close as possible" to the correct distribution.

(通过正确的分配我的意思了非整数的分布,我还没有完全确定我的意思是尽可能接近。也许有一些有效的输出,只要他们总的原始值。)

(By correct distribution I mean the non-integer distribution, and I haven't fully defined what I mean by "as close as possible." There are perhaps several valid outputs, so long as they total the original value.)

推荐答案

分发第一股如预期。现在你有一个简单的问题,有一个较少的参与方,并可供分配量减少。重复,直到没有更多的参与者。

Distribute the first share as expected. Now you have a simpler problem, with one fewer participants, and a reduced amount available for distribution. Repeat until there are no more participants.

>>> 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
...
>>>

这篇关于分发使用权整数?如何计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆