[英]Convert a list of floats to the nearest whole number if greater than x in Python
[英]How to check if a list of floats adds up to a whole number?
我想找到浮点数列表的总和并检查它是否是整数:
l = [0.85, 0.85, 0.15, 0.15]
显然, l
的总和是 2.0。 但 Python 不同意,由于浮点数限制:
> sum(l)
1.9999999999999998
因此,我选择的方法sum(l).is_integer()
将返回False
。
评估列表是否为整数的更好方法是什么?
您可以使用decimal
包。
>>> from decimal import Decimal
>>> l = [Decimal(x) for x in ['0.85', '0.85', '0.15', '0.15']]
>>> s = sum(l)
>>> s
Decimal('2.00')
>>> s == int(s)
True
您可以结合使用math.isclose
和内置的round
函数。
>>> from math import isclose
>>> l = [0.85, 0.85, 0.15, 0.15]
>>> s = sum(l)
>>> isclose(s, round(s))
True
当您需要精确算术时,最好的解决方案是仅使用整数。 在这种情况下,您可以将每个输入四舍五入到 2 或 3 个小数位以进行检查。
l = [0.85, 0.85, 0.15, 0.15]
number_of_places = 3
multiplier = 10 ** number_of_places
>>> sum(int(round(x*multiplier)) for x in l)
2000
>>> sum(int(round(x*multiplier)) for x in l) % multiplier == 0
True
除了小数,您还可以使用分数模块,它可以处理任意分母,例如:
from fractions import Fraction
print(Fraction(1,3) + Fraction(4,7) + Fraction(2,21))
也适用于Fraction('0.85') + Fraction('0.15')
或Fraction('2/6')
。
请注意,添加 Fractions 的结果是一个 Fraction,最终分母 == 1,因此,您必须替换为分母检查,或 int 转换的相等性,而不是测试is_integer()
:
collection = [Fraction(each) for each in ['0.85', '0.85', '0.15', '0.15']]
sum = sum(collection)
print(sum.denominator == 1)
print(int(sum) == sum)
在包括 Smalltalk 在内的一些语言中,当分母为 1 时,分数会自动减少为整数,从而使代码不那么脆弱……
^((1/3) + (4/7) + (2/21)) isInteger
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.