New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
int(float) may return a long for no reason #55353
Comments
On 32 bits, there is no reason to get a 'long' here: >>> int(float(sys.maxint))
2147483647L
>>> int(int(float(sys.maxint)))
2147483647
>>> int(float(-sys.maxint-1))
-2147483648L
>>> int(int(float(-sys.maxint-1)))
-2147483648 On 64 bits, it's another story because floats cannot store 64 bits of precision. However, -sys.maxint-1 can still be represented exactly in a float, and the same issue occurs: >>> int(float(-sys.maxint-1))
-9223372036854775808L
>>> int(int(float(-sys.maxint-1)))
-9223372036854775808 |
I'm not sure whether this is a bug, though. So I'd be skeptical that it should be changed in 2.x, even if the cause was identified. |
I'd call this a bug, albeit a minor one. The documentation for 'int' says: "If the argument is outside the integer range a long object will be returned instead." ... which certainly suggests (without actually formally implying) that an int object should be returned if the argument is within the integer range. |
Ah ok. I agree it's a bug, then. |
This turns out to be a one-line fix (modulo comments and tests); see attached patch. The new code depends on the assumption that C longs are represented using two's complement, but note that this assumption is (a) already present elsewhere in the Python core (e.g., in the definition of bitwise operations for ints), and (b) universally true in practice (as far as I'm aware). For theoretical completeness, it would be easy to write a different test for ones' complement and sign-magnitude machines, but in practice that seems pointless, and given the near-impossibility of testing that code, I left it out. |
Very smart! |
New changeset e1ebec2446cd by Mark Dickinson in branch '2.7': |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: