# If Else Statements In Numpy Arange

## 10 February 2022 - 1 answer

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?

``````In : first = np.arange(18.5, 24.99, 0.01)
In : first.shape
Out: (649,)
In : first[:10]
Out:
array([18.5 , 18.51, 18.52, 18.53, 18.54, 18.55, 18.56, 18.57, 18.58,
18.59])
In : x=22.03
``````

`x` isn't "found"

``````In : x in first
Out: False
``````

Let's look for a close match:

``````In : np.nonzero(np.isclose(x,first))
Out: (array(),)
In : first
Out: 22.030000000000552
``````

The closest match is still a bit off - due to floating point calculations. 'in/equal' tests on floating point values are not reliable.

`arange` recommends `linspace` when using float steps. The resulting values are a closer match to our expectations:

``````In : first1 = np.linspace(18.5,24.98,len(first))
In : np.nonzero(np.isclose(x,first1))
Out: (array(),)
In : first1
Out: 22.03
In : x in first1
Out: True
``````

There still is a potential for a float mismatch.

To better see the full precision of the floats, lets display the arrays as lists

``````In : first[:10].tolist()
Out:
[18.5,
18.51,
18.520000000000003,
18.530000000000005,
18.540000000000006,
18.550000000000008,
18.56000000000001,
18.57000000000001,
18.580000000000013,
18.590000000000014]
In : first1[:10].tolist()
Out: [18.5, 18.51, 18.52, 18.53, 18.54, 18.55, 18.56, 18.57, 18.58, 18.59]
``````