Care needs to be taken when checking for equality between floating point numbers, and should usually be done with a tolerance in mind, using e.g. numpy.allcose.
Question 1: Is it safe to check for the occurrence of a specific floating point number using the "in" keyword (or are there similar keywords/functions for this purpose)? Example:
if myFloatNumber in myListOfFloats:
print('Found it!')
else:
print('Sorry, no luck.')
Question 2: If not, what would be a neat and tidy solution?
If you don't compute your floats in the same place or with the exact same equation, then you might have false negatives with this code (because of rounding errors). For example:
In this case, we can just have a custom "
in
" function that will actually make this true (in this case it may be better/faster to usenumpy.isclose
instead ofnumpy.allclose
):There is an important note in the documentation:
The note adds that
atol
is not zero contrary tomath.isclose
'sabs_tol
. If you need a custom tolerance when usingclose_to_any
, use thekwargs
to passrtol
and/oratol
down to numpy. In the end, your existing code would translate to this:Or you could have some options
close_to_any(myFloatNumber, myListOfFloats, atol=1e-12)
, note that1e-12
is arbitrary and you shouldn't use this value unless you have a good reason to.Coming back to the rounding error we observed in the first example, this would give: