zain
zain

Reputation: 13

Java multiplication of same number returns different output in Python

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

Answers (3)

Michael Szczesny
Michael Szczesny

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

Dev-vruper
Dev-vruper

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

Mureinik
Mureinik

Reputation: 312106

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

long vi = 3997125L * 3997125L;

Upvotes: 3

Related Questions