Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange error in python3 when doing big int calculation

I was trying to do this in Python 3.5.2:

int(204221389795918291262976/10000)

but got the unexpected result: 20422138979591827456

It's working fine in Python 2.7.12, result is: 20422138979591829126L

Any idea why Python 3 gave me the wrong result?

like image 600
EricY Avatar asked Sep 03 '16 15:09

EricY


People also ask

How does Python handle large integers?

Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long and is separate from the int type, but the interpreter will automatically use whichever is more appropriate.

How big can integers be in Python?

These represent numbers in the range -2147483648 through 2147483647. (The range may be larger on machines with a larger natural word size, but not smaller.)


1 Answers

In python 3 you have to use integer division // explicitly or else float division will apply even between 2 integers.

That's one of the major changes between python 2 and python 3

In your example: (will work both in python 2 and python 3 so it's backwards compatible!)

204221389795918291262976//10000
20422138979591829126

(you don't even need to convert to int here, result is int since both terms are int)

BTW if you want to make this bug work with python 2 it is also possible :)

from __future__ import division
like image 142
Jean-François Fabre Avatar answered Oct 01 '22 21:10

Jean-François Fabre