Distributing integers using weights? How to calculate?

前端 未结 4 394
鱼传尺愫
鱼传尺愫 2020-12-10 09:03

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 colum

4条回答
  •  再見小時候
    2020-12-10 09:56

    If you expect distributing 3 with weights of (1,2,3) to be equal to (0.5, 1, 1.5), then the rounding is your problem:

    weighted_value = round(p*total)
    

    You want:

    weighted_value = p*total
    

    EDIT: Solution to return integer distribution

    def distribute(total, distribution):
      leftover = 0.0
      distributed_total = []
      distribution_sum = sum(distribution)
      for weight in distribution:
        weight = float(weight)
        leftover, weighted_value = modf(weight*total/distribution_sum + leftover)
        distributed_total.append(weighted_value)
      distributed_total[-1] = round(distributed_total[-1]+leftover) #mitigate round off errors
      return distributed_total
    

提交回复
热议问题