Search code examples
pythonindexingrounding-error

Finding a float in a list by index method with rounding error(Python)


So often , the value we got are affected by rounding errors, when we operate on floats numbers e.g. 1.000000000001, if I want to find a value like 1.0 in the list, what's the cleanest way of doing it? I was trying to find the index of 1.0, and so to find the corresponding y value in y list.I have thought about using a if statement, to find x value within a certain range, such as 1.0+/-0.0000000000001, I'm sure there is a better way of doing it. Thanks for everyone.

xlist=[0,1.0000000000001,2.0.3.0]
ylist=[0.0,1.0,2.0,3.0]
def numberfinder(xlist=[],ylist=[]):
    return ylist[xlist.index(1.0)]

print numberfinder(xlist,ylist)

Solution

  • You should round both lists first as given below:

    xlist=[round(i,1) for i in xlist]
    ylist=[round(i,1) for i in ylist]
    

    Now xlist will become:

    [0.0, 1.0, 2.0, 3.0]
    

    and 1.0 can be found.