Reputation: 13
I am porting some Java code to Python, but for some reason, the results differ.
Java
int vi = 3997125 * 3997125;
Output: -270075495
Python
vi = 3997125 * 3997125
Output: 15977008265625
How would I accomplish the same output Java returns in Python?
Upvotes: 1
Views: 106
Reputation: 5026
To simulate the conversion of a python integer to 32bit integer value with overflow
def bit32(value):
shift = 1 << 32
return value % shift - shift if value.bit_length() >= 32 else value
bit32(3997125*3997125)
Out:
-270075495
Upvotes: 1
Reputation: 430
The range of a variable declared as type int
is -2,147,483,648 to 2,147,483,647 .
So when you do
3997125 * 3997125 = 15,977,008,265,625
which is out of range for a int type .
As suggested you can change the type to long
.
Upvotes: 1