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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…