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

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

    I liked @Sesquipedal 's suggestion but with modification (a special use case when both values are 0 returns False). In my case I was on Python 2.7 and just used a simple function:

    if f1 ==0 and f2 == 0:
        return True
    else:
        return abs(f1-f2) < tol*max(abs(f1),abs(f2))
    

提交回复
热议问题