5
votes

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?

1
Your first error was assuming similar results, really. Python 2 and Python 3 share many similar traits but also differ in various aspects. Don't take behavior in one implementation granted for another. - Dimitris Fasarakis Hilliard

1 Answers

6
votes

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