What is the best way to compare floats for almost-equality in Python?

后端 未结 15 1453
旧时难觅i
旧时难觅i 2020-11-21 05:07

It\'s well known that comparing floats for equality is a little fiddly due to rounding and precision issues.

For example: https://randomascii.wordpress.com/2012/02/2

相关标签:
15条回答
  • 2020-11-21 05:57

    If you want to use it in testing/TDD context, I'd say this is a standard way:

    from nose.tools import assert_almost_equals
    
    assert_almost_equals(x, y, places=7) #default is 7
    
    0 讨论(0)
  • 2020-11-21 05:59

    Useful for the case where you want to make sure 2 numbers are the same 'up to precision', no need to specify the tolerance:

    • Find minimum precision of the 2 numbers

    • Round both of them to minimum precision and compare

    def isclose(a,b):                                       
        astr=str(a)                                         
        aprec=len(astr.split('.')[1]) if '.' in astr else 0 
        bstr=str(b)                                         
        bprec=len(bstr.split('.')[1]) if '.' in bstr else 0 
        prec=min(aprec,bprec)                                      
        return round(a,prec)==round(b,prec)                               
    

    As written, only works for numbers without the 'e' in their string representation ( meaning 0.9999999999995e-4 < number <= 0.9999999999995e11 )

    Example:

    >>> isclose(10.0,10.049)
    True
    >>> isclose(10.0,10.05)
    False
    
    0 讨论(0)
  • 2020-11-21 06:01

    For some of the cases where you can affect the source number representation, you can represent them as fractions instead of floats, using integer numerator and denominator. That way you can have exact comparisons.

    See Fraction from fractions module for details.

    0 讨论(0)
  • 2020-11-21 06:01

    This maybe is a bit ugly hack, but it works pretty well when you don't need more than the default float precision (about 11 decimals).

    The round_to function uses the format method from the built-in str class to round up the float to a string that represents the float with the number of decimals needed, and then applies the eval built-in function to the rounded float string to get back to the float numeric type.

    The is_close function just applies a simple conditional to the rounded up float.

    def round_to(float_num, prec):
        return eval("'{:." + str(int(prec)) + "f}'.format(" + str(float_num) + ")")
    
    def is_close(float_a, float_b, prec):
        if round_to(float_a, prec) == round_to(float_b, prec):
            return True
        return False
    
    >>>a = 10.0
    10.0
    >>>b = 10.0001
    10.0001
    >>>print is_close(a, b, prec=3)
    True
    >>>print is_close(a, b, prec=4)
    False
    

    Update:

    As suggested by @stepehjfox, a cleaner way to build a rount_to function avoiding "eval" is using nested formatting:

    def round_to(float_num, prec):
        return '{:.{precision}f}'.format(float_num, precision=prec)
    

    Following the same idea, the code can be even simpler using the great new f-strings (Python 3.6+):

    def round_to(float_num, prec):
        return f'{float_num:.{prec}f}'
    

    So, we could even wrap it up all in one simple and clean 'is_close' function:

    def is_close(a, b, prec):
        return f'{a:.{prec}f}' == f'{b:.{prec}f}'
    
    0 讨论(0)
  • 2020-11-21 06:02

    I found the following comparison helpful:

    str(f1) == str(f2)
    
    0 讨论(0)
  • 2020-11-21 06:03

    Python 3.5 adds the math.isclose and cmath.isclose functions as described in PEP 485.

    If you're using an earlier version of Python, the equivalent function is given in the documentation.

    def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
        return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
    

    rel_tol is a relative tolerance, it is multiplied by the greater of the magnitudes of the two arguments; as the values get larger, so does the allowed difference between them while still considering them equal.

    abs_tol is an absolute tolerance that is applied as-is in all cases. If the difference is less than either of those tolerances, the values are considered equal.

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