EricY
EricY

Reputation: 123

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?

Upvotes: 5

Views: 276

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140256

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

Upvotes: 6

Related Questions