2

Can someone explain, what's going on here? And what is the best practice of how to properly / robustly check if something is contained within an array?

Python 3.9.6 (default, Jun 30 2021, 10:22:16) 
[GCC 11.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> np.__version__
'1.20.3'
>>> np.linspace(0,1,11)
array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
>>> 0.5 in np.linspace(0,1,11)
True
>>> 0.6 in np.linspace(0,1,11)
False
>>> np.isin(0.6, np.linspace(0,1,11))
array(False)
>>> 0.6 in np.round(np.linspace(0,1,11), 1)
True
Suuuehgi
  • 4,547
  • 3
  • 27
  • 32

1 Answers1

2

if you don't have to be that precise you can use something like np.isclose. You can provide tolerance values if you want.
for example:

>>> a = np.linspace(0,1,11)
>>> any(np.isclose(a,.6))
True
Suuuehgi
  • 4,547
  • 3
  • 27
  • 32
alparslan mimaroğlu
  • 1,450
  • 1
  • 10
  • 20
  • Thank you! I think `isclose` is the way to go here. I slightly adapted your answer for brevity / clarity. – Suuuehgi Aug 13 '21 at 20:51