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

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

    I would agree that Gareth's answer is probably most appropriate as a lightweight function/solution.

    But I thought it would be helpful to note that if you are using NumPy or are considering it, there is a packaged function for this.

    numpy.isclose(a, b, rtol=1e-05, atol=1e-08, equal_nan=False)
    

    A little disclaimer though: installing NumPy can be a non-trivial experience depending on your platform.

提交回复
热议问题