Python百分比舍入

Jer*_*eng 5 python rounding

我知道如何在Python中四舍五入,这不是一个简单的技术问题。

我的问题是,从技术上讲,四舍五入将使一组百分比之和不等于100%。

例如:

a = 1
b = 14
Run Code Online (Sandbox Code Playgroud)

我想计算(a + b)中a和(a + b)中b的百分比。

答案应该是

a/(a + b) = 1/15 
b/(a + b) = 14/15
Run Code Online (Sandbox Code Playgroud)

当我尝试四舍五入这些数字时,我得到了

1/15 = 6.66 
14/15 = 93.33 
Run Code Online (Sandbox Code Playgroud)

(我正在做地板),这使得这两个数字之和不等于100%。

在这种情况下,我们应该将1/15的上限设置为6.67,将14/15的上限设置为93.33。现在,它们加起来达到100%。在这种情况下,规则应为“四舍五入到最接近的数字”

但是,如果情况更复杂,请说3个数字:

a = 1
b = 7
c = 7
Run Code Online (Sandbox Code Playgroud)

地板:

1/15 = 6.66
7/15 = 46.66
7/15 = 46.66
Run Code Online (Sandbox Code Playgroud)

总计不等于100%。

天花板:

1/15 = 6.67
7/15 = 46.67
7/15 = 46.67
Run Code Online (Sandbox Code Playgroud)

总计不等于100%。

四舍五入(至最接近的数字)与上限相同。仍不等于100%。

所以我的问题是,在任何情况下我该怎么做以确保它们的总和为100%。

提前致谢。

更新:感谢您的评论提示。我从重复的帖子答案中获取了“最大余数”解决方案。

代码是:

def round_to_100_percent(number_set, digit_after_decimal=2):
    """
        This function take a list of number and return a list of percentage, which represents the portion of each number in sum of all numbers
        Moreover, those percentages are adding up to 100%!!!
        Notice: the algorithm we are using here is 'Largest Remainder'
        The down-side is that the results won't be accurate, but they are never accurate anyway:)
    """
    unround_numbers = [x / float(sum(number_set)) * 100 * 10 ** digit_after_decimal for x in number_set]
    decimal_part_with_index = sorted([(index, unround_numbers[index] % 1) for index in range(len(unround_numbers))], key=lambda y: y[1], reverse=True)
    remainder = 100 * 10 ** digit_after_decimal - sum([int(x) for x in unround_numbers])
    index = 0
    while remainder > 0:
        unround_numbers[decimal_part_with_index[index][0]] += 1
        remainder -= 1
        index = (index + 1) % len(number_set)
    return [int(x) / float(10 ** digit_after_decimal) for x in unround_numbers]
Run Code Online (Sandbox Code Playgroud)

经过测试,似乎工作正常。

Tri*_*m21 -2

欢迎来到 IEEE 浮点数。

Python 中数学运算返回的浮点数是近似值。对于某些值,百分比总和将大于 100。

您有两种解决方案:使用fractiondecimal模块 OR,只是不希望它们加起来达到 100%。

  • 是的,但它没有回答这个问题:“所以我的问题是我应该做什么来确保它们在任何情况下加起来都达到 100%。” (PS:不是投反对票的人) (2认同)