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

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

提交回复
热议问题