'If else statements in numpy arange

Basicaly I want to compare a variable between two np.arange()

x = 22.03
first = np.arange(18.5, 24.99, 0.01)
second = np.arange(25.0, 29.99, 0.01)

if x in first:
    print("x is in first")
elif x in second:
    print("x is in second")

I expect to see "x isin first" but rather I get nothing printed on the terminal. If I add another else: statement it will execute whatever is in that.

I am using numpy because I want to have a range of floats. The native range() function doesn't support floats

There happens no comparison between the two, why is that?



Solution 1:[1]

x = 22.03
first = np.arange(18.5, 24.99, 0.01)
second = np.arange(25.0, 29.99, 0.01)

type(first)
Out[13]: numpy.ndarray

# cast to list and proper value rounding for boolean comparison
first = [round(n, 2) for n in first]

x in first
Out[16]: True

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Goran B.