Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a list of floats adds up to a whole number?

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?

like image 284
n1000 Avatar asked Dec 13 '22 09:12

n1000


2 Answers

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
like image 144
Dave Radcliffe Avatar answered Feb 23 '23 13:02

Dave Radcliffe


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
like image 45
CDJB Avatar answered Feb 23 '23 13:02

CDJB