I would like to find the sum of a list of floats and check if it is a whole number or not:
l = [0.85, 0.85, 0.15, 0.15]
The sum of l
is 2.0, obviously. But Python does not agree, due to floating point limitations:
> sum(l)
1.9999999999999998
Therefore my method of choice, sum(l).is_integer()
, will return False
.
What would be a better method to evaluate if lists sum to a whole number?
You can use the decimal
package.
>>> 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
You can use a combination of math.isclose
and the inbuilt round
function.
>>> from math import isclose
>>> l = [0.85, 0.85, 0.15, 0.15]
>>> s = sum(l)
>>> isclose(s, round(s))
True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With