1

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?

3
  • You want the wrong (overflow) result in python? Commented Dec 15, 2020 at 13:31
  • Yeah. A bit odd, I know. @MichaelSzczesny Commented Dec 15, 2020 at 13:32
  • In Java, an int is signed so that anything above 2^31 will be treated as a negative number. So if the output is > 2^31 then do 2^31 - (value) instead. Commented Dec 15, 2020 at 13:39

3 Answers 3

3

The Java snippet overflows. To avoid this, you could use longs:

long vi = 3997125L * 3997125L;
Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Updated my answer to work with integers without overflow.
1

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 .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.