我知道如何在Python中四舍五入,这不是一个简单的技术问题。
我的问题是四舍五入会使一组百分比加起来不等于100%,而从技术上讲,它们应该等于100%。
例如:a = 1
b = 14
我想计算a在(a + b)和b在(a + b)中的百分比
答案应该是
a/(a + b) = 1/15
b/(a + b) = 14/15
当我尝试四舍五入时,我得到
1/15 = 6.66
14/15 = 93.33
(我在做地板),这使得这两个数字加起来不是100%。
在这种情况下,我们应该为1/15做天花板,这是6.67,地板为14/15,这是93.33。现在它们加起来是100%。在这种情况下,规则应该是"四舍五入到最接近的数字"
然而,如果我们有一个更复杂的情况,说3个数字:
a = 1
b = 7
c = 7
地板:
1/15 = 6.66
7/15 = 46.66
7/15 = 46.66
加起来不等于100%。
上限:
1/15 = 6.67
7/15 = 46.67
7/15 = 46.67
不等于100%。
四舍五入(到最接近的数字)与上限相同。还是不能加到100%
所以我的问题是我应该做些什么来确保它们在任何情况下都是100%。
提前感谢。
更新:感谢评论中的提示。我从重复的Post答案中取了"最大余数"解。
代码是:
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]
测试,似乎工作良好
正如其他人所评论的那样,如果您的数字像您的示例中那样漂亮且四舍五入,则可以使用fractions模块来保持有理数的准确性:
In [2]: from fractions import Fraction
In [5]: a = Fraction(1)
In [6]: b = Fraction(14)
In [7]: a/(a+b)
Out[7]: Fraction(1, 15)
In [8]: a/(a+b) + (b/(a+b))
Out[8]: Fraction(1, 1)
如果是奇数分数,这显然不太好
欢迎参加IEEE Floats。
python中数学运算返回的浮点数是近似值。对于某些值,百分比之和将大于100。
您有两种解决方案:使用fraction
或decimal
模块or,只是不希望它们相加为100%。