Wednesday, June 26, 2019

python - Losing float precision in for loop

I have a list of floats taken from an sqlite3 db. From it I want to find the first two numbers greater than a number, say 18 in this case, and enumerate their position in the db.



The db list:



pr = [(20.49999999999983,), (16.29999999999967,), (13.799999999999102,), (18.600000000000705,), (9.600000000000364,), (11.599999999999966,), (25.30000000000001,)...]


Hence I try the following:




fnd =([i[0] for i in pr if i[0] > 18])
>>> [20.49999999999983, 18.600000000000705, 25.30000000000001]

for j in fnd:
print ([i for i,k in enumerate(pr) if k == j])


For which I get 3 empty lists. I am assuming my problem comes from the fact that the float is being rounded when I use the for loop.



for j in fnd:

print j

>>>20.5, 18.6, 25.3


Can anyone offer a workaround?

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...