在处理一个问题时,我偶然发现了一些我自己无法解决的问题.
我有一个变量:
a = pow(2, 1024)
它的类型是long int.如果我尝试将它明确地转换为浮动,就像float(a)我收到的那样OverflowError.这个数字太大了,不适合64位浮点数,所以这是可以理解的.
然后我尝试使用隐式转换,通过浮点数将其拖放:
b = a * 11.0
再次,OverflowError发生时,这是很好的,因为根据python文档,从长整型的隐式转换到浮动发生.结果就像以前一样.
最后,我尝试比较:
a > 11.0
回报True.将OverflowError不会发生.这让我很困惑.如果不需要数字以相同的格式,Python比较机制如何工作?按照这个,
Python完全支持混合算术:当二进制算术运算符具有不同数值类型的操作数时,具有"较窄"类型的操作数被扩展为另一个的操作数,其中普通整数比长整数窄,比浮点更窄,比浮点更窄.复杂.混合类型数量之间的比较使用相同的规则.构造函数int(),long(),float()和complex()可用于生成特定类型的数字.
我的问题是,为什么a不在前面提到的比较中被抛弃?
我使用的Python版本是2.7.15.谢谢你提前
从来源:
/* 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) a long 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.
*/
Run Code Online (Sandbox Code Playgroud)
因此,考虑了转换的潜在缺陷.