0

I have been chasing an error for a long time. I have finally tracked it down to this:

a = 3*np.arange(0.5,1.6,0.1)
b = 3*np.array([0.5,1,1.5])

for c in a:
   print(c in b)

I would expect 3 of the elements of a to appear in b but when I execute the code above I only get that one of them is in b. Is anyone able to explain whats going on here?

MasonTep
  • 11
  • 1
  • Try changing it to `print(c, c in b)` and you'll see the problem. – Barmar Apr 08 '21 at 20:23
  • Print the `repr()` of each element - in the `a` array, you'll see the values `2.9999999999999996` and `4.499999999999999` instead of `3.0` and `4.5`. You should never directly compare floats to each other. If you want to have infinite precision, I believe you can use the `decimal` module in this case. – Random Davis Apr 08 '21 at 20:24

0 Answers0