2

I am getting wrong results when I do an element wise comparison on a numpy array of floats.

For eg:

import numpy as np
a = np.arange(4, 5 + 0.025, 0.025)
print a

mask = a==5.0
print mask

na = a[mask]
print na

When I run the above code, a == 5.0 doesn't give me a True value for the index where the value is in fact 5.0 I also tried setting the dtype of array to numpy.double thinking it could be a floating point precision issue but it still returns me wrong result.

I am pretty sure I am missing something here....can anyone point me to right direction or tell me what's wrong with the code above?

Thanks!

bhavesh
  • 41
  • 5
  • As a temporary fix, I have to actually do: abs(a - 5.0) <0.00001 to get it to give me correct/expected answer but I would still love to know if there is a better way of doing this? – bhavesh Jun 14 '16 at 11:15
  • probably floating point issue, for instance see [this question](http://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate) – DomTomCat Jun 14 '16 at 11:15
  • try using `linspace` instead of `arange`. – hpaulj Jun 14 '16 at 16:50

1 Answers1

1

There is an imprecision here when using float types, use np.isclose to compare an array against a scalar float value:

In [50]:
mask = np.isclose(a,5.0)
print(mask)
na = a[mask]
na

[False False False False False False False False False False False False
 False False False False False False False False False False False False
 False False False False False False False False False False False False
 False False False False  True False]
Out[50]:
array([ 5.])
EdChum
  • 376,765
  • 198
  • 813
  • 562
  • Thanks! I was trying to see if there is some function like that. Thanks for the quick answer. – bhavesh Jun 14 '16 at 11:19
  • Actually my build of numpy doesn't have isclose method. But I can mark it as the answer. – bhavesh Jun 14 '16 at 11:22
  • You must be using an old version I suggest upgrading if possible – EdChum Jun 14 '16 at 11:23
  • I recommend being careful when using functions to make approximations. It is always a good thing to have an epson value which may vary according to your problem. – Ricardo Silveira Jun 14 '16 at 11:25
  • @RicardoSilveira `np.isclose` takes an epsilon absolute or relative param, the default is `1e-05` and `1e-08` respectively – EdChum Jun 14 '16 at 11:27