-1
>>> import numpy as np
>>> a=np.arange(0,2,0.2)
>>> a
array([ 0. ,  0.2,  0.4,  0.6,  0.8,  1. ,  1.2,  1.4,  1.6,  1.8])
>>> a=a.tolist()
>>> a
[0.0, 0.2, 0.4, 0.6000000000000001, 0.8, 1.0, 1.2000000000000002, 1.4000000000000001, 1.6, 1.8]
>>> a.index(0.6)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 0.6 is not in list

it appears that some values in the list have changed and I can't find them with index(). How can I fix that?

toine
  • 1,946
  • 18
  • 24
pomxipum
  • 315
  • 1
  • 3
  • 9
  • possible duplicate of [python limiting floats to two decimal points](http://stackoverflow.com/questions/455612/python-limiting-floats-to-two-decimal-points) – Cory Kramer Jun 26 '14 at 15:55

1 Answers1

5

0.6 hasn't changed; it was never there:

>>> import numpy as np
>>> a = np.arange(0, 2, 0.2)
>>> a
array([ 0. ,  0.2,  0.4,  0.6,  0.8,  1. ,  1.2,  1.4,  1.6,  1.8])
>>> 0.0 in a
True # yep!
>>> 0.6 in a
False # what? 
>>> 0.6000000000000001 in a
True # oh...

The numbers in the array are rounded for display purposes, but the array really contains the value you subsequently see in the list; 0.6000000000000001. 0.6 cannot be precisely represented as a float, therefore it is unwise to rely on floating-point numbers comparing precisely equal!

One way to find the index is to use a tolerance approach:

def float_index(seq, f):
    for i, x in enumerate(seq):
         if abs(x - f) < 0.0001:
             return i

which will work on the array too:

>>> float_index(a, 0.6)
3
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437