Skip to content Skip to sidebar Skip to footer

Python - Converting An Array To A List Causes Values To Change

>>> 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() >&

Solution 1:

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.0in a
True# yep!>>> 0.6in a
False# what? >>> 0.6000000000000001in 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:

deffloat_index(seq, f):
    for i, x inenumerate(seq):
         ifabs(x - f) < 0.0001:
             return i

which will work on the array too:

>>>float_index(a, 0.6)
3

Post a Comment for "Python - Converting An Array To A List Causes Values To Change"