python 'in' operator returning the wrong value

python

Solution

The problem is that `4.0` is not in the array. A value very close to 4.0, but slightly off (due to floating point inaccuracies) is in the array, and when you print it, the printing routine is rounding to "4.0" for display purposes.

If you print out the actual element (`loggs[5]`), python will print with more precision, and you will see the value is actually slightly higher than `4.0` (approximately `4.0000000000000018`).

I recommend reading What Every Computer Scientist Should Know About Floating-Point Arithmetic for more details.

Problem

I ran into a weird issue with the 'in' operator for python, which is reproduced from the ipython shell below: ``` In [119]: Teff = 10000 In [120]: loggs = numpy.arange(4.5, 4*numpy.log10(Teff) - 15.02, -0.1) In [121]: 4.0 in loggs Out[121]: False In [122]: loggs Out[122]: array([ 4.5, 4.4, 4.3, 4.2, 4.1, 4. , 3.9, 3.8, 3.7, 3.6, 3.5, 3.4, 3.3, 3.2, 3.1, 3. , 2.9, 2.8, 2.7, 2.6, 2.5, 2.4, 2.3, 2.2, 2.1, 2. , 1.9, 1.8, 1.7, 1.6, 1.5, 1.4, 1.3, 1.2, 1.1, 1. ]) ``` As you can see, 4.0 is in the array, but the 'in' operator returns False. I tried this same thing with '4' (an integer) and '4.', both with the same result. Same with other values in that array (like 3.9). Any ideas? I am running python 2.7.1, with numpy version 1.7.0. I saw a previous post that is close, but there was never a good answer for what happened with 'in'.

Original source

Related problems