0

I'm using NumPy's arange() method and trying to figure why my value, which is seemingly in range, does not return True when applied.

3.0 in np.arange(3, 3.9, .01)

Returns True which is expected. However, the following returns false:

3.2 in np.arange(3, 3.9, .01)

I also verified the values the np.arange() expression generates. The IDE showed 3.2000 as a valid value, adding the trailing zeros did not change the result.. In addition, the following expression returns True, which again I expect:

1.7 in np.arange(0, 3, .01)
  • You might not have 3.2, check the values in the `array` property, I have `3.1999999999999957` and `3.2099999999999955`. [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Guy Aug 08 '21 at 06:11
  • `in` (`__contains__`) uses `==` testing. With floats it is better to use `np.isclose`, which tests the absolute difference. This handles the small differences (on the order of 1e-15) that we can expect in float values. – hpaulj Aug 08 '21 at 07:15

1 Answers1

0

The reason is that you are using np.arange() with a non-integer step, which is known to be inconsistent. Taken from np.arange() documentation:

When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use numpy.linspace for these cases.

ranger = np.arange(3,3.9, .01)
linspacer = np.linspace(3,3.89,90)

print(3.2 in ranger)
print(3.2 in linspacer)

The first statement will return False, where the second statement will return True.

kwonhj77
  • 1
  • 1