[英]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.