When does Python perform type conversion when comparing int and float?

前端 未结 7 1492
太阳男子
太阳男子 2021-01-12 23:22

Why does Python return True when I compare int and float objects which have the same value?

For example:

>&         


        
7条回答
  •  误落风尘
    2021-01-13 00:14

    You can have a look at the source code for the CPython implementation.

    The function is preceded by this comment explaining how the conversion is attempted:

    /* Comparison is pretty much a nightmare.  When comparing float to float,
     * we do it as straightforwardly (and long-windedly) as conceivable, so
     * that, e.g., Python x == y delivers the same result as the platform
     * C x == y when x and/or y is a NaN.
     * When mixing float with an integer type, there's no good *uniform* approach.
     * Converting the double to an integer obviously doesn't work, since we
     * may lose info from fractional bits.  Converting the integer to a double
     * also has two failure modes:  (1) an int may trigger overflow (too
     * large to fit in the dynamic range of a C double); (2) even a C long may have
     * more bits than fit in a C double (e.g., on a 64-bit box long may have
     * 63 bits of precision, but a C double probably has only 53), and then
     * we can falsely claim equality when low-order integer bits are lost by
     * coercion to double.  So this part is painful too.
     */
    

    Other implementations are not guaranteed to follow the same logic.

提交回复
热议问题