Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...