using list operator “in” with floating point values

前端 未结 3 2023
迷失自我
迷失自我 2021-01-14 11:34

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 \"so         


        
相关标签:
3条回答
  • 2021-01-14 11:40

    You can use numpy.isclose() instead of Python's in.

    import numpy as np
    other_list = np.array([474.251001, 123.456])
    number = other_list[0]
    number = round(number, 3)
    if number == 474.251:
        print "number == 474.251"
    if number in other_list:
        print "number in other_list"
    if any(np.isclose(number, other_list, rtol=1e-7)):
        print 'any(np.isclose(number, other_list, rtol=1e-7))'
    

    Output:

    number == 474.251
    any(np.isclose(number, other_list, rtol=1e-7))
    
    0 讨论(0)
  • 2021-01-14 11:46

    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.

    0 讨论(0)
  • 2021-01-14 12:04

    You could also following an approach, where you compare the values based on an arbitrary precision.

    For example, convert all your floats like this:

    def internalPrecision(number):
        precision = 1000
        return int(round(number * precision)) 
    

    If you do this, both operators == and in should work.

    0 讨论(0)
提交回复
热议问题