你得到一个空数组的原因是严格的值2.0
实际上并不存在于您的数组中。
例如:
In [2]: x = np.arange(1.4, 2.4, 0.05)
In [3]: x
Out[3]:
array([ 1.4 , 1.45, 1.5 , 1.55, 1.6 , 1.65, 1.7 , 1.75, 1.8 ,
1.85, 1.9 , 1.95, 2. , 2.05, 2.1 , 2.15, 2.2 , 2.25,
2.3 , 2.35])
In [4]: x == 2.0
Out[4]:
array([False, False, False, False, False, False, False, False, False,
False, False, False, False, False, False, False, False, False,
False, False], dtype=bool)
In [5]: np.where(x == 2.0)
Out[5]: (array([], dtype=int64),)
这是浮点数学限制的经典陷阱。如果你愿意,你可以这样做:
y[np.isclose(x, 2)]
然而,一般来说,您希望在给定的 x 处插入 y 值。
例如,假设您想要的值为2.01
。该值不存在于您的 x 数组中。
相反,使用np.interp
进行线性插值:
In [6]: y = np.cos(x)
In [7]: np.interp(2.01, x, y)
Out[7]: -0.4251320075130563