- A+

While working on an issue, I stumbled at something I cannot really undestand on my own.

I have a variable: `a = pow(2, 1024)`

Its type is long int. If I try casting it explicitly to float, like `float(a)`

, I receive `OverflowError`

. The number is too big to fit in 64bit float, so it's understandable.

Then I try implicit cast, through mutliplying it by a float number:

`b = a * 11.0`

Once again, the `OverflowError`

occurs, which is fine, because according to python docs, implicit conversion from long int to float happens. So the result is like before.

Finally, I try comparison:

`a > 11.0`

returns `True`

. The `OverflowError`

doesn't occur. And that confuses me a lot. How does the Python comparison mechanism work, if it doesn't require numerics to be in the same format? Accordind to this,

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 pointis narrower than complex.Comparisons between numbers of mixed type use the same rule.The constructors int(), long(), float(), and complex() can be used to produce numbers of a specific type.

My question is, why `a`

is not being cast to float in forementioned comparison?

The version of Python I'm using is 2.7.15. Thanks in an advance

From the source:

`/* 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. */ `

As such, the potential pitfalls of conversion are taken into account.