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

后端 未结 15 2013
旧时难觅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: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
    

提交回复
热议问题