如何使圆形百分数加起来为100% [英] How to make rounded percentages add up to 100%

查看:367
本文介绍了如何使圆形百分数加起来为100%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面四个百分比,再psented为浮动数字$ P $:

Consider the four percentages below, represented as float numbers:

    13.626332%
    47.989636%
     9.596008%
    28.788024%
   -----------
   100.000000%

我需要重新present这些百分比为整数。如果我只是使用 Math.round(),我结束了一个总数为101%。

I need to represent these percentages as whole numbers. If I simply use Math.round(), I end up with a total of 101%.

14 + 48 + 10 + 29 = 101

如果我用 parseInt()函数,我结束了一个总的97%。

If I use parseInt(), I end up with a total of 97%.

13 + 47 + 9 + 28 = 97

什么是好的算法来重新present任意数量的比例为整数,同时仍保持了总数的100%?

What's a good algorithm to represent any number of percentages as whole numbers while still maintaining a total of 100%?

修改:读了一些意见和答案后,明显有很多方式去解决这个

Edit: After reading some of the comments and answers, there are clearly many ways to go about solving this.

在我的脑海里,保持真实的数字,正确的结果是一个最小化的总体误差,通过误差较大的舍入将如何介绍相对于实际值定义的:

In my mind, to remain true to the numbers, the "right" result is the one that minimizes the overall error, defined by how much error rounding would introduce relative to the actual value:

        value  rounded     error               decision
   ----------------------------------------------------
    13.626332       14      2.7%          round up (14)
    47.989636       48      0.0%          round up (48)
     9.596008       10      4.0%    don't round up  (9)
    28.788024       29      2.7%          round up (29)

在出现平局(3.33,3.33,3.33),可以做成任意的决定(例如,3,4,3)。

In case of a tie (3.33, 3.33, 3.33) an arbitrary decision can be made (e.g. 3, 4, 3).

推荐答案

由于没有这里的答案似乎妥善解决这个问题,这是一个使用的 underscorejs

Since none of the answers here seem to solve it properly, here's my semi-obfuscated version using underscorejs:

function foo(l, target) {
    var off = target - _.reduce(l, function(acc, x) { return acc + Math.round(x) }, 0);
    return _.chain(l).
            sortBy(function(x) { return Math.round(x) - x }).
            map(function(x, i) { return Math.round(x) + (off > i) - (i >= (l.length + off)) }).
            value();
}

foo([13.626332, 47.989636, 9.596008, 28.788024], 100) // => [48, 29, 14, 9]
foo([16.666, 16.666, 16.666, 16.666, 16.666, 16.666], 100) // => [17, 17, 17, 17, 16, 16]
foo([33.333, 33.333, 33.333], 100) // => [34, 33, 33]
foo([33.3, 33.3, 33.3, 0.1], 100) // => [34, 33, 33, 0]

这篇关于如何使圆形百分数加起来为100%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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