Python - Converting an array to a list causes values to change -
Python - Converting an array to a list causes values to change -
>>> import numpy np >>> a=np.arange(0,2,0.2) >>> array([ 0. , 0.2, 0.4, 0.6, 0.8, 1. , 1.2, 1.4, 1.6, 1.8]) >>> a=a.tolist() >>> [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 phone call last): file "<stdin>", line 1, in <module> valueerror: 0.6 not in list
it appears values in list have changed , can't find them index(). how can prepare that?
0.6 hasn't changed; it never there:
>>> import numpy np >>> = np.arange(0, 2, 0.2) >>> array([ 0. , 0.2, 0.4, 0.6, 0.8, 1. , 1.2, 1.4, 1.6, 1.8]) >>> 0.0 in true # yep! >>> 0.6 in false # what? >>> 0.6000000000000001 in true # oh... the numbers in array rounded display purposes, array contains value subsequently see in list; 0.6000000000000001. 0.6 cannot exactly represented float, hence unwise rely on floating-point numbers comparing exactly equal!
one way find index utilize tolerance approach:
def float_index(seq, f): i, x in enumerate(seq): if abs(x - f) < 0.0001: homecoming which work on array too:
>>> float_index(a, 0.6) 3 python arrays list numpy
Comments
Post a Comment