When does Python perform type conversion when comparing int and float?
当我比较具有相同值的
例如:
1 2 | >>> 5*2 == 5.0*2.0 >>> True |
Objects of different types, except different numeric types, never compare equal.
号
还有:
Python fully supports mixed arithmetic: when a binary arithmetic operator has operands of different numeric types, the operand with the"narrower" type is widened to that of the other, where integer is narrower than floating point, which is narrower than complex. Comparisons between numbers of mixed type use the same rule.
https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex
号
比较逻辑由每种类型的
您可以查看cpython实现的源代码。
函数前面是解释如何尝试转换的注释:
1
2
3
4
5
6
7
8
9
10
11
12
13
14 /* 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.
*/
号
其他实现不能保证遵循相同的逻辑。
简单的答案是语言是这样设计的。以下是支持这一点的文档的摘录:
6.10.1价值比较
Numbers of built-in numeric types (Numeric Types — int, float, complex) and of the standard library types fractions.Fraction and decimal.Decimal can be compared within and across their types, with the restriction that complex numbers do not support order comparison.
号
换句话说,我们希望具有相同值的不同数字类型相等。
PEP 20
Special cases aren't special enough to break the rules.
Although practicality beats purity.
号
除了在最常见的情况下使生活变得困难之外,使数字类型不具有可比性还有什么好处?
从文档中:
Python fully supports mixed arithmetic: when a binary arithmetic
operator has operands of different numeric types, the operand with the
"narrower" type is widened to that of the other, where plain integer
is narrower than long integer is narrower than floating point is
narrower than complex. Comparisons between numbers of mixed type use
the same rule.
号
根据这个5*2扩大到10.0,等于10.0如果您正在比较混合数据类型,那么结果将在具有长范围的数据类型的基础上考虑,因此在您的情况下,浮点范围大于int最大浮点数可以是1.7976931348623157E+308整数最大值可以是-->9223372036854775807
谢谢
==运算符只比较值,而不比较类型。您可以使用"is"关键字实现与在其他语言中使用==相同的效果。例如
1 | 5 is 5.0 |
号
退货假
1 | == |
是比较运算符
你实际上是在问解释器你的表达方式的两边是否相等。
换句话说,您要求它返回一个布尔值,而不是转换数据类型。如果要转换数据类型,则必须在代码中隐式转换。