Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using list operator "in" with floating point values

Tags:

python

numpy

I have a list with floats, each number with 3 decimals (eg. 474.259). If I verify the number in the list like this:

if 474.259 in list_sample:
    print "something!"

Then the message is shown, but if I take the number from another list and I round it:

number = other_list[10]
number = round(number, 3)
if number == 474.259:
    print "the numbers are same!"
if number in list_sample:
    print "something!"

The second message is not shown.

like image 289
Hocine Ben Avatar asked Dec 07 '25 14:12

Hocine Ben


1 Answers

Comparing floating point numbers for exact equality usually won't do what you want. This is because floating point numbers in computers have a representation (storage format) which is inherently inaccurate for many real numbers.

I suggest reading about it here: http://floating-point-gui.de/ and doing something like a "fuzzy compare" using an "epsilon" tolerance value to consider the numbers equal so long as they differ by less than x% or whatever.

like image 140
John Zwinck Avatar answered Dec 09 '25 03:12

John Zwinck