考虑下面四个百分比,用浮点数表示:

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

我需要用整数表示这些百分比。如果我简单地使用Math.round(),我最终得到的总数是101%。

14 + 48 + 10 + 29 = 101

如果我使用parseInt(),我最终得到了97%。

13 + 47 + 9 + 28 = 97

有什么好的算法可以将任何百分比数表示为整数,同时还保持总数为100%?


编辑:在阅读了一些评论和回答后,显然有很多方法可以解决这个问题。

在我看来,为了保持数字的真实性,“正确”的结果是最小化总体误差的结果,定义为相对于实际值会引入多少误差舍入:

        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)。


当前回答

注意:选择的答案是改变数组的顺序,这不是首选的,在这里我提供了更多不同的变化,以实现相同的结果,并保持数组的顺序

讨论

给定[98.88,.56,.56]你想怎么四舍五入呢?你有四种选择

1-四舍五入,并从其余数字中减去加法,因此结果为[98,1,1]

这可能是一个很好的答案,但是如果我们有[97.5,.5,.5,.5,.5,.5]呢?然后你需要四舍五入到[95,1,1,1,1,1]

你明白是怎么回事了吗?如果你添加更多类似0的数字,你将从剩下的数字中失去更多的值。当你有一个像[40,.5,.5,…, 5]。当你四舍五入时,你可以得到一个1的数组:[1,1,....1)

所以集合不是一个好选择。

2-四舍五入。所以[98.88,.56,.56]变成[98,0,0],那么你比100少2。你忽略任何已经为0的数,然后把它们的差加起来,得到最大的数。所以越大的数字就会得到越多。

3-和前面一样,向下四舍五入,但你根据小数降序排序,根据小数划分差异,所以最大的小数将得到差异。

4-四舍五入,但你把你加到下一个数字上的数加起来。就像一个波一样,你添加的东西会被重定向到数组的末尾。所以[98.88,.56,.56]变成了[99,0,1]

这些都不是理想的,所以要注意您的数据会失去形状。

在这里,我为情况2和3提供了一个代码(因为当你有很多类似零的数字时,情况1是不实际的)。它是现代的Js,不需要任何库来使用

2例

const v1 = [13.626332, 47.989636, 9.596008, 28.788024];// => [ 14, 48, 9, 29 ]
const v2 = [16.666, 16.666, 16.666, 16.666, 16.666, 16.666] // => [ 17, 17, 17, 17, 16, 16 ] 
const v3 = [33.333, 33.333, 33.333] // => [ 34, 33, 33 ]
const v4 = [33.3, 33.3, 33.3, 0.1] // => [ 34, 33, 33, 0 ]
const v5 = [98.88, .56, .56] // =>[ 100, 0, 0 ]
const v6 = [97.5, .5, .5, .5, .5, .5] // => [ 100, 0, 0, 0, 0, 0 ]

const normalizePercentageByNumber = (input) => {
    const rounded: number[] = input.map(x => Math.floor(x));
    const afterRoundSum = rounded.reduce((pre, curr) => pre + curr, 0);
    const countMutableItems = rounded.filter(x => x >=1).length;
    const errorRate = 100 - afterRoundSum;
    
    const deductPortion = Math.ceil(errorRate / countMutableItems);
    
    const biggest = [...rounded].sort((a, b) => b - a).slice(0, Math.min(Math.abs(errorRate), countMutableItems));
    const result = rounded.map(x => {
        const indexOfX = biggest.indexOf(x);
        if (indexOfX >= 0) {
            x += deductPortion;
            console.log(biggest)
            biggest.splice(indexOfX, 1);
            return x;
        }
        return x;
    });
    return result;
}

3例

const normalizePercentageByDecimal = (input: number[]) => {

    const rounded= input.map((x, i) => ({number: Math.floor(x), decimal: x%1, index: i }));

    const decimalSorted= [...rounded].sort((a,b)=> b.decimal-a.decimal);
    
    const sum = rounded.reduce((pre, curr)=> pre + curr.number, 0) ;
    const error= 100-sum;
    
    for (let i = 0; i < error; i++) {
        const element = decimalSorted[i];
        element.number++;
    }

    const result= [...decimalSorted].sort((a,b)=> a.index-b.index);
    
    return result.map(x=> x.number);
}

4例

你只需要计算在每次汇总的数字中增加或减去多少额外的空气,然后在下一项中再增加或减去它。

const v1 = [13.626332, 47.989636, 9.596008, 28.788024];// => [14, 48, 10, 28 ]
const v2 = [16.666, 16.666, 16.666, 16.666, 16.666, 16.666] // => [17, 16, 17, 16, 17, 17]
const v3 = [33.333, 33.333, 33.333] // => [33, 34, 33]
const v4 = [33.3, 33.3, 33.3, 0.1] // => [33, 34, 33, 0]

const normalizePercentageByWave= v4.reduce((pre, curr, i, arr) => {

    let number = Math.round(curr + pre.decimal);
    let total = pre.total + number;

    const decimal = curr - number;

    if (i == arr.length - 1 && total < 100) {
        const diff = 100 - total;
        total += diff;
        number += diff;
    }

    return { total, numbers: [...pre.numbers, number], decimal };

}, { total: 0, numbers: [], decimal: 0 });

其他回答

如果你真的必须四舍五入,这里已经有了很好的建议(最大余数,最小相对误差,等等)。

也有一个很好的理由不四舍五入(你至少会得到一个“看起来更好”但“错误”的数字),以及如何解决这个问题(警告你的读者),这就是我所做的。

让我加上“错误”的数字部分。

假设你有三个事件/实体/…用一些百分比来近似:

DAY 1
who |  real | app
----|-------|------
  A | 33.34 |  34
  B | 33.33 |  33
  C | 33.33 |  33

稍后,值略有变化,为

DAY 2
who |  real | app
----|-------|------
  A | 33.35 |  33
  B | 33.36 |  34
  C | 33.29 |  33

第一个表有前面提到的“错误”数字的问题:33.34更接近33而不是34。

但现在误差更大了。与第2天和第1天相比,A的实际百分比值增加了0.01%,但近似值显示下降了1%。

这是一个定性错误,可能比最初的定量错误更严重。

你可以为整个集合设计一个近似值,但是,你可能必须在第一天发布数据,因此你不知道第二天的情况。所以,除非你真的,真的,必须近似,否则最好不要。

不要把四舍五入的数字相加。你会得到不准确的结果。总数可能会显著偏离,这取决于术语的数量和小数部分的分布。

显示四舍五入的数字,但和实际值。根据你呈现数字的方式不同,实际的方法也会有所不同。这样你就能得到

14 48 10 29 __ 100

不管怎样,都会有差异。在你的例子中,没有办法显示加起来等于100的数字而不以错误的方式“舍入”一个值(最小的错误是将9.596更改为9)

EDIT

你需要在以下选项中做出选择:

项目的准确性 和的准确性(如果你是四舍五入的值) 四舍五入的项目与四舍五入的总和的一致性)

大多数情况下,当处理百分比时,第三种方法是最好的选择,因为当总数等于101%时比当单个项目的总数不等于100时更明显,并且您可以保持单个项目的准确性。“舍入”9.596到9在我看来是不准确的。

为了解释这一点,我有时会添加一个脚注,解释各个值是四舍五入的,可能不是100% -任何理解四舍五入的人都应该能够理解这个解释。

注意:选择的答案是改变数组的顺序,这不是首选的,在这里我提供了更多不同的变化,以实现相同的结果,并保持数组的顺序

讨论

给定[98.88,.56,.56]你想怎么四舍五入呢?你有四种选择

1-四舍五入,并从其余数字中减去加法,因此结果为[98,1,1]

这可能是一个很好的答案,但是如果我们有[97.5,.5,.5,.5,.5,.5]呢?然后你需要四舍五入到[95,1,1,1,1,1]

你明白是怎么回事了吗?如果你添加更多类似0的数字,你将从剩下的数字中失去更多的值。当你有一个像[40,.5,.5,…, 5]。当你四舍五入时,你可以得到一个1的数组:[1,1,....1)

所以集合不是一个好选择。

2-四舍五入。所以[98.88,.56,.56]变成[98,0,0],那么你比100少2。你忽略任何已经为0的数,然后把它们的差加起来,得到最大的数。所以越大的数字就会得到越多。

3-和前面一样,向下四舍五入,但你根据小数降序排序,根据小数划分差异,所以最大的小数将得到差异。

4-四舍五入,但你把你加到下一个数字上的数加起来。就像一个波一样,你添加的东西会被重定向到数组的末尾。所以[98.88,.56,.56]变成了[99,0,1]

这些都不是理想的,所以要注意您的数据会失去形状。

在这里,我为情况2和3提供了一个代码(因为当你有很多类似零的数字时,情况1是不实际的)。它是现代的Js,不需要任何库来使用

2例

const v1 = [13.626332, 47.989636, 9.596008, 28.788024];// => [ 14, 48, 9, 29 ]
const v2 = [16.666, 16.666, 16.666, 16.666, 16.666, 16.666] // => [ 17, 17, 17, 17, 16, 16 ] 
const v3 = [33.333, 33.333, 33.333] // => [ 34, 33, 33 ]
const v4 = [33.3, 33.3, 33.3, 0.1] // => [ 34, 33, 33, 0 ]
const v5 = [98.88, .56, .56] // =>[ 100, 0, 0 ]
const v6 = [97.5, .5, .5, .5, .5, .5] // => [ 100, 0, 0, 0, 0, 0 ]

const normalizePercentageByNumber = (input) => {
    const rounded: number[] = input.map(x => Math.floor(x));
    const afterRoundSum = rounded.reduce((pre, curr) => pre + curr, 0);
    const countMutableItems = rounded.filter(x => x >=1).length;
    const errorRate = 100 - afterRoundSum;
    
    const deductPortion = Math.ceil(errorRate / countMutableItems);
    
    const biggest = [...rounded].sort((a, b) => b - a).slice(0, Math.min(Math.abs(errorRate), countMutableItems));
    const result = rounded.map(x => {
        const indexOfX = biggest.indexOf(x);
        if (indexOfX >= 0) {
            x += deductPortion;
            console.log(biggest)
            biggest.splice(indexOfX, 1);
            return x;
        }
        return x;
    });
    return result;
}

3例

const normalizePercentageByDecimal = (input: number[]) => {

    const rounded= input.map((x, i) => ({number: Math.floor(x), decimal: x%1, index: i }));

    const decimalSorted= [...rounded].sort((a,b)=> b.decimal-a.decimal);
    
    const sum = rounded.reduce((pre, curr)=> pre + curr.number, 0) ;
    const error= 100-sum;
    
    for (let i = 0; i < error; i++) {
        const element = decimalSorted[i];
        element.number++;
    }

    const result= [...decimalSorted].sort((a,b)=> a.index-b.index);
    
    return result.map(x=> x.number);
}

4例

你只需要计算在每次汇总的数字中增加或减去多少额外的空气,然后在下一项中再增加或减去它。

const v1 = [13.626332, 47.989636, 9.596008, 28.788024];// => [14, 48, 10, 28 ]
const v2 = [16.666, 16.666, 16.666, 16.666, 16.666, 16.666] // => [17, 16, 17, 16, 17, 17]
const v3 = [33.333, 33.333, 33.333] // => [33, 34, 33]
const v4 = [33.3, 33.3, 33.3, 0.1] // => [33, 34, 33, 0]

const normalizePercentageByWave= v4.reduce((pre, curr, i, arr) => {

    let number = Math.round(curr + pre.decimal);
    let total = pre.total + number;

    const decimal = curr - number;

    if (i == arr.length - 1 && total < 100) {
        const diff = 100 - total;
        total += diff;
        number += diff;
    }

    return { total, numbers: [...pre.numbers, number], decimal };

}, { total: 0, numbers: [], decimal: 0 });

对于那些在熊猫系列中有百分比的人,这里是我的最大余数方法的实现(就像Varun Vohra的答案一样),在那里你甚至可以选择你想要四舍五入的小数。

import numpy as np

def largestRemainderMethod(pd_series, decimals=1):

    floor_series = ((10**decimals * pd_series).astype(np.int)).apply(np.floor)
    diff = 100 * (10**decimals) - floor_series.sum().astype(np.int)
    series_decimals = pd_series - floor_series / (10**decimals)
    series_sorted_by_decimals = series_decimals.sort_values(ascending=False)

    for i in range(0, len(series_sorted_by_decimals)):
        if i < diff:
            series_sorted_by_decimals.iloc[[i]] = 1
        else:
            series_sorted_by_decimals.iloc[[i]] = 0

    out_series = ((floor_series + series_sorted_by_decimals) / (10**decimals)).sort_values(ascending=False)

    return out_series

您可以尝试跟踪由于舍入而产生的误差,如果累计误差大于当前数字的小数部分,则再反向舍入。

13.62 -> 14 (+.38)
47.98 -> 48 (+.02 (+.40 total))
 9.59 -> 10 (+.41 (+.81 total))
28.78 -> 28 (round down because .81 > .78)
------------
        100

不确定这是否适用于一般情况,但如果顺序相反,似乎也会有类似的效果:

28.78 -> 29 (+.22)
 9.59 ->  9 (-.37; rounded down because .59 > .22)
47.98 -> 48 (-.35)
13.62 -> 14 (+.03)
------------
        100

我相信在某些情况下,这种方法可能会失效,但任何方法都至少在某种程度上是任意的,因为您基本上是在修改输入数据。